Get ahead
VMware offers training and certification to turbo-charge your progress.
Learn moreOn behalf of the team and all contributors, I am pleased to announce that Spring Batch 6.1 is available from Maven Central now!
This release brings a number of new features, enhancements and bug fixes, as well as a few breaking changes, on top of 6.0.
For the complete list of changes, please check the release notes.
This blog post walks you through the major changes in 6.1:
@JobParameter annotation for injecting job parametersPageableItemReaderRepositoryItemWriterJsonLineMapper agnostic to the JSON libraryJsonLineAggregatorspring-batch-coreJdbcClientSpring dependencies are upgraded to the following versions:
@JobParameter annotation for injecting job parametersInjecting a job parameter into a job or step scoped bean used to require a SpEL expression, which is only evaluated at runtime and is easy to get wrong. The new @JobParameter annotation is a shorter alternative that defaults the name of the job parameter to the name of the annotated field or parameter:
@Bean
@StepScope
public FlatFileItemReader<Foo> fooReader(@JobParameter String inputFile) {
return new FlatFileItemReaderBuilder<Foo>()
.resource(new FileSystemResource(inputFile))
// other properties omitted
.build();
}
This replaces @Value("#{jobParameters['inputFile']}"). The name can also be specified explicitly, for example @JobParameter("input.file.name"). Like the expression it replaces, it is meant for beans defined in the job or step scope. When the name is omitted on a method or constructor parameter, the code must be compiled with the -parameters flag, which is the default with the Spring Boot Maven and Gradle plugins. See issue #5563 for more details.
PageableItemReaderPageableItemReader is a type-safe alternative to RepositoryItemReader. Instead of invoking a repository method reflectively by name, it takes a function from a Spring Data Pageable to a Slice, which is checked at compile time:
PageableItemReader<Customer> reader = new PageableItemReaderBuilder<Customer>()
.query(customerRepository::findAll)
.sort(Sort.by(Sort.Direction.ASC, "id"))
.pageSize(100)
.name("customerReader")
.build();
The sort can also be expressed with Spring Data's type-safe property references, for example Sort.by(Sort.Direction.ASC, Customer::getId), which eliminates string-based property names.
MultiResourceItemReaderBuilder now accepts resource location patterns directly (for example "classpath:data/input/file-*.txt"), removing the need to resolve and inject resources beforehand. A new ResourcesItemReaderBuilder brings the same capability to ResourcesItemReader.
The MongoDB job repository now supports a configurable collection prefix, similar to the table prefix of the JDBC job repository. This makes it possible to run several applications against the same MongoDB database, or to isolate environments from each other:
@EnableBatchProcessing
@EnableMongoJobRepository(collectionPrefix = "MY_APP_")
class MyJobConfiguration {
// job definition omitted
}
The prefix defaults to BATCH_, so existing applications are not affected.
RepositoryItemWriterRepositoryItemWriter now supports flushing the underlying Spring Data repository after writing a chunk, either by naming a repository method that both saves and flushes (such as saveAllAndFlush), or by overriding the new flush method in a subclass.
JsonLineMapper agnostic to the JSON libraryJsonLineMapper could only map each line of a JSON Lines file to a Map<String, Object>, and only with Jackson. It is now generic and delegates the conversion of a line to a new JsonObjectUnmarshaller, which makes it independent of the JSON library and able to map lines to any type, such as a domain class or a record. Implementations based on Jackson and Gson are provided:
record Trade(String isin, int quantity, double price, String customer) {
}
FlatFileItemReader<Trade> reader = new FlatFileItemReaderBuilder<Trade>()
.name("tradeReader")
.resource(resource)
.lineMapper(new JsonLineMapper<>(new JacksonJsonObjectUnmarshaller<>(Trade.class)))
// or .lineMapper(new JsonLineMapper<>(new GsonJsonObjectUnmarshaller<>(Trade.class)))
.build();
The no-argument constructor and the constructor that takes a JsonMapper are deprecated in favor of JsonLineMapper(JsonObjectUnmarshaller), and are scheduled for removal in version 7.0. This is a source and binary breaking change for code that uses the raw JsonLineMapper type and calls mapLine directly on it. Code that only passes the mapper to a reader needs no changes beyond a recompile. See the reference documentation for more details.
JsonLineAggregatorJsonLineAggregator is the writer-side counterpart of JsonLineMapper: a LineAggregator that makes it possible to write items to a JSON Lines file with a FlatFileItemWriter. Like the mapper, it is agnostic to the JSON library, as it delegates the conversion of an item to a JsonObjectMarshaller, so either the Jackson or the Gson implementation can be used:
FlatFileItemWriter<Trade> writer = new FlatFileItemWriterBuilder<Trade>()
.name("tradeWriter")
.resource(new FileSystemResource("trades.jsonl"))
.lineAggregator(new JsonLineAggregator<>(new JacksonJsonObjectMarshaller<>()))
.build();
spring-batch-coreAsyncItemProcessor, AsyncItemWriter, and ChunkTaskExecutorItemWriter have moved from spring-batch-integration to org.springframework.batch.core.step.item in spring-batch-core, since they only rely on a TaskExecutor and have no dependency on Spring Integration. This lets applications use asynchronous item processing and local chunking without pulling in spring-batch-integration and its transitive dependencies. The classes in spring-batch-integration are kept as deprecated subclasses for backward compatibility.
A few builders (FlatFileItemReaderBuilder, FlatFileItemWriterBuilder, JdbcBatchItemWriterBuilder) exposed pairs of methods configuring mutually exclusive strategies, only failing at build() time when both were called. These builders now use a staged DSL, so invalid combinations are rejected by the compiler instead. This is a source and binary breaking change for code that stores the builder's return value in a variable typed as the builder class; fluent call chains need no changes beyond a recompile. See issue #4888 for more details.
JdbcClientThe JDBC implementations of the job repository DAOs (JdbcJobInstanceDao, JdbcJobExecutionDao, JdbcStepExecutionDao and JdbcExecutionContextDao) now use Spring Framework's JdbcClient instead of JdbcOperations to access the batch metadata tables. This gives them named parameters and a single fluent API for queries, updates and batch updates. The client is a required collaborator, so it is now passed to the constructor:
JdbcJobInstanceDao jobInstanceDao = new JdbcJobInstanceDao(JdbcClient.create(dataSource));
Applications that configure the job repository through @EnableBatchProcessing, @EnableJdbcJobRepository, JdbcDefaultBatchConfiguration, JdbcJobRepositoryFactoryBean or JobExplorerFactoryBean are not affected, as these build the DAOs themselves. This is however a source and binary breaking change for code that instantiates these DAOs directly, since their no-argument constructors have been removed. Accordingly, AbstractJdbcBatchMetadataDao#setJdbcTemplate(JdbcOperations) and #getJdbcTemplate() are deprecated in favor of the new constructor and of #getJdbcClient(). See issue #4804 for more details.
This release makes several parts of the job repository and of partitioned steps faster and lighter on memory. Here are the biggest gains.
Restarting a job used to read the full history of its job instance, loading every past execution with all its steps. So the more often a job was restarted, the more SQL statements each restart needed: on v6.0.4, the 12th restart of the same failed job issued 130 statements, 8 more for each past execution. Now only the last execution is checked, so the cost of a restart no longer depends on the history. This is also available in v6.0.6.
Finding the executions of a job instance is faster too. JdbcJobExecutionDao#findJobExecutions used to run 3 extra queries for each execution (1 + 3N queries for N executions). It now needs 2 queries, whatever N is. For a job instance with 10 executions, that is 2 queries instead of 31, which is about 15 times fewer. getLastJobExecution goes from 4 queries to 2, which is half as many.
MessageChannelPartitionHandler regularly asks the job repository if its workers are done. Each time, it used to load the step execution of every worker, and each of them came with the whole job execution and all its step executions. With many partitions, this adds up quickly: in one reported case, a step with 837 partitions kept 837 × 837 = 700,569 StepExecution objects in memory, and the node polling the workers used 15 GB of memory, 10 times more than another node doing the same amount of work (1.5 GB).
The handler now only counts the running workers, with the new JobRepository#countRunningStepExecutions(Collection<Long>), and loads the job execution once, when all workers are done. In the same case, that is 837 objects instead of 700,569, which is 837 times fewer, and it removes the extra memory of the polling node: about 10 times less memory. The new methods are default methods, so existing JobRepository implementations still work, and the handler falls back to the previous behavior if counting is not supported.
A few more queries were removed from the JDBC DAOs. Each one saves one query every time it applies:
JOB_EXECUTION table.SELECT COUNT(*) first to check that the row exists, since the update itself reports a missing row.JdbcJobExecutionDao#synchronizeStatus(StepExecution) saves one query.The last two are also available in v6.0.6.
This release introduces the following breaking changes, each of them described in the sections above:
FlatFileItemReaderBuilder, FlatFileItemWriterBuilder and JdbcBatchItemWriterBuilder changed (source and binary incompatible).AvroItemReader/AvroItemWriter jobs with a SpecificRecord or plain Java item type fail at runtime unless the item type is explicitly trusted.JdbcClient: the no-argument constructors of the JDBC DAOs were removed (source and binary incompatible).JsonLineMapper is now agnostic to the JSON library: the raw type changes (source and binary incompatible).Please refer to the What's new section of the reference documentation for details about each of them.
Several APIs have been deprecated in this release in favor of their replacements when applicable, including Apache Derby support, the legacy date/time converters, the AsyncItemProcessor, AsyncItemWriter and ChunkTaskExecutorItemWriter classes of spring-batch-integration, and a few count methods on JobRepository/JobExplorer/JobInstanceDao. For the full list, please refer to the reference documentation.
I would like to thank all contributors who had a role in this release! We look forward to your feedback on Github Issues, Github Discussions and X.