Description
Status quo in Spring Batch 4.x
In Spring Batch 4.x, it is not possible to pass a lambda or method reference to SimpleStepBuilder::processor
.
The method is overloaded to accept either an ItemProcessor
or a Function
, which both qualify as functional interfaces. This makes passing a lambda ambivalent if it is not explicitly cast to one of the two. In my opinion, the casts that need to be applied to pass lambdas are unnecessarily ceremonial and feel clunky in modern Java that strongly favors lambdas over explicit Function
.
In other words, it would be great if one could write
stepBuilderFactory.get("multiplyBy2Step")
.<Integer, Integer>chunk(chunkSize)
.reader(itemReader())
.processor(i -> i * 2)
.writer(itemWriter())
.build();
instead of either
stepBuilderFactory.get("multiplyBy2Step")
.<Integer, Integer>chunk(chunkSize)
.reader(itemReader())
.processor((ItemProcessor<Integer, Integer>) i -> i * 2)
.writer(itemWriter())
.build();
or
stepBuilderFactory.get("multiplyBy2Step")
.<Integer, Integer>chunk(chunkSize)
.reader(itemReader())
.processor((Function<Integer, Integer>) i -> i * 2)
.writer(itemWriter())
.build();
Feature request for Spring Batch 5.0
To allow lambdas and method references to be passed directly to SimpleStepBuilder::processor
, please consider to drop the possibility to pass Function
. If the method only accepted ItemProcessor
, passing a lambda would not be ambivalent and not require a cast.
This is a breaking change in a central DSL but I think Spring Batch 5.0 is the perfect moment to do this.
From my perspective, most applications would need to simply drop casts to Function
to migrate from 4.x to 5.0. Applications that do use actual Function
objects as arguments for SimpleStepBuilder::processor
would need to replace code like
stepBuilderFactory.get("step")
.<Integer, Integer>chunk(chunkSize)
.reader(itemReader())
.processor(function)
.writer(itemWriter())
.build();
with
stepBuilderFactory.get("step")
.<Integer, Integer>chunk(chunkSize)
.reader(itemReader())
.processor(function::apply)
.writer(itemWriter())
.build();
for a straight-forward migration approach.