### Complete Step Restart Configuration Example Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/chunk-oriented-processing/restart.adoc Complete example showing how to configure restartable Spring Batch jobs with different step configurations. Includes steps with start limits, steps that always run, and regular steps. Demonstrates building job flows with multiple steps having different restart behaviors. ```java @Bean public Job footballJob(JobRepository jobRepository, Step playerLoad, Step gameLoad, Step playerSummarization) { return new JobBuilder("footballJob", jobRepository) .start(playerLoad) .next(gameLoad) .next(playerSummarization) .build(); } @Bean public Step playerLoad(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("playerLoad", jobRepository) .chunk(10).transactionManager(transactionManager) .reader(playerFileItemReader()) .writer(playerWriter()) .build(); } @Bean public Step gameLoad(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("gameLoad", jobRepository) .allowStartIfComplete(true) .chunk(10).transactionManager(transactionManager) .reader(gameFileItemReader()) .writer(gameWriter()) .build(); } @Bean public Step playerSummarization(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("playerSummarization", jobRepository) .startLimit(2) .chunk(10).transactionManager(transactionManager) .reader(playerSummarizationSource()) .writer(summaryWriter()) .build(); } ``` ```xml ``` -------------------------------- ### XML Configuration Example (Conditional Flow) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/controlling-flow.adoc Shows an XML configuration example using the `next` element to control flow based on `ExitStatus`. This example demonstrates using 'FAILED', 'COMPLETED WITH SKIPS', and '*' patterns. ```XML ``` -------------------------------- ### Java Configuration Example (Conditional Flow) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/controlling-flow.adoc Shows a Java configuration example using the `on()` method to control flow based on `ExitStatus`. This example demonstrates using 'FAILED', 'COMPLETED WITH SKIPS', and '*' patterns. ```Java @Bean public Job job(JobRepository jobRepository, Step step1, Step step2, Step errorPrint1) { return new JobBuilder("job", jobRepository) .start(step1).on("FAILED").end() .from(step1).on("COMPLETED WITH SKIPS").to(errorPrint1) .from(step1).on("*").to(step2) .end() .build(); } ``` -------------------------------- ### JobStep Example (XML) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/controlling-flow.adoc Provides an XML example demonstrating the implementation of a JobStep, which runs a separate job execution. ```xml ... ``` -------------------------------- ### Example Tasklet Implementation Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/tasklet.adoc An example Tasklet implementation that deletes files in a specified directory. The execute method is called once, and the tasklet can be referenced in a step configuration. ```java public class FileDeletingTasklet implements Tasklet, InitializingBean { private Resource directory; public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { File dir = directory.getFile(); Assert.state(dir.isDirectory(), "The resource must be a directory"); File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { boolean deleted = files[i].delete(); if (!deleted) { throw new UnexpectedJobExecutionException("Could not delete file " + files[i].getPath()); } } return RepeatStatus.FINISHED; } public void setDirectoryResource(Resource directory) { this.directory = directory; } public void afterPropertiesSet() throws Exception { Assert.state(directory != null, "Directory must be set"); } } ``` -------------------------------- ### XML Configuration for Spring Batch Job Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/processor.adoc This is an XML configuration example for a Spring Batch job, outlining the setup of a step with an ItemReader, ItemProcessor, and ItemWriter. ```xml <job id="ioSampleJob"> <step name="step1"> <tasklet> <chunk reader="fooReader" processor="fooProcessor" writer="barWriter" commit-interval="2"/> </tasklet> </step> </job> ``` -------------------------------- ### FlatFileItemWriter Configuration Example (Java & XML) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/readers-and-writers/flat-files/file-item-writer.adoc Demonstrates how to configure FlatFileItemWriter using both Java configuration with FlatFileItemWriterBuilder and XML configuration. Both examples set the resource and use PassThroughLineAggregator. ```java @Bean public FlatFileItemWriter itemWriter() { return new FlatFileItemWriterBuilder() .name("itemWriter") .resource(new FileSystemResource("target/test-outputs/output.txt")) .lineAggregator(new PassThroughLineAggregator<>()) .build(); } ``` ```xml ``` -------------------------------- ### MS SQLServer Sequence Creation for Spring Batch 5 Source: https://github.com/spring-projects/spring-batch/wiki/Spring-Batch-5.0-Migration-Guide SQL script to create sequences for MS SQLServer in Spring Batch 5. New applications can use this directly. Existing applications might need to adjust the START WITH value based on previous sequence table values. ```sql CREATE SEQUENCE BATCH_STEP_EXECUTION_SEQ START WITH 0 MINVALUE 0 MAXVALUE 9223372036854775807 NO CACHE NO CYCLE; CREATE SEQUENCE BATCH_JOB_EXECUTION_SEQ START WITH 0 MINVALUE 0 MAXVALUE 9223372036854775807 NO CACHE NO CYCLE; CREATE SEQUENCE BATCH_JOB_SEQ START WITH 0 MINVALUE 0 MAXVALUE 9223372036854775807 NO CACHE NO CYCLE; ``` -------------------------------- ### Declarative Iteration with AOP Configuration Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/repeat.adoc Demonstrates programmatic and XML-based configuration of declarative iteration using Spring AOP. The Java example shows ProxyFactory setup with RepeatOperationsInterceptor, while the XML example shows pointcut and advisor configuration. Both approaches wrap method calls in RepeatOperations for automatic retry logic based on CompletionPolicy. ```java @Bean public MyService myService() { ProxyFactory factory = new ProxyFactory(RepeatOperations.class.getClassLoader()); factory.setInterfaces(MyService.class); factory.setTarget(new MyService()); MyService service = (MyService) factory.getProxy(); JdkRegexpMethodPointcut pointcut = new JdkRegexpMethodPointcut(); pointcut.setPatterns(".*processMessage.*"); RepeatOperationsInterceptor interceptor = new RepeatOperationsInterceptor(); ((Advised) service).addAdvisor(new DefaultPointcutAdvisor(pointcut, interceptor)); return service; } ``` ```xml ``` -------------------------------- ### SystemCommandTasklet CommandRunner Strategy (Java) Source: https://github.com/spring-projects/spring-batch/wiki/Spring-Batch-5.0-Migration-Guide This code demonstrates the introduction of the CommandRunner interface in SystemCommandTasklet, decoupling command execution. The JvmCommandRunner is the default implementation using java.lang.Runtime#exec. ```java // Interface for running system commands public interface CommandRunner { void run(String... args) throws IOException; } // Default implementation using Runtime.exec public class JvmCommandRunner implements CommandRunner { @Override public void run(String... args) throws IOException { Runtime.getRuntime().exec(args); } } ``` -------------------------------- ### End-to-End Test Batch Job with XML Configuration Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/testing.adoc Illustrates an end-to-end test for a Spring Batch job using JUnit 5 and XML configuration. Similar to the Java configuration example, this test prepares the 'CUSTOMER' table with data, executes the job via JobOperatorTestUtils, and verifies the 'COMPLETED' status. It depends on Spring Batch test utilities and JdbcTemplate for data setup and assertion. ```java @SpringBatchTest @SpringJUnitConfig(locations = { "/skip-sample-configuration.xml" }) public class SkipSampleFunctionalTests { @Autowired private JobOperatorTestUtils jobOperatorTestUtils; private JdbcTemplate jdbcTemplate; @Autowired public void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } @Test public void testJob(@Autowired Job job) throws Exception { this.jobOperatorTestUtils.setJob(job); this.jdbcTemplate.update("delete from CUSTOMER"); for (int i = 1; i <= 10; i++) { this.jdbcTemplate.update("insert into CUSTOMER values (?, 0, ?, 100000)", i, "customer" + i); } JobExecution jobExecution = jobOperatorTestUtils.startJob(); Assert.assertEquals("COMPLETED", jobExecution.getExitStatus().getExitCode()); } } ``` -------------------------------- ### Configure TradeItemWriter in Spring (Java and XML) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/common-patterns.adoc Demonstrates wiring the TradeItemWriter as a footerCallback for a FlatFileItemWriter. The Java example uses @Bean definitions, while the XML example provides equivalent bean configuration. These snippets are useful for setting up flat file writing with custom footers. ```java @Bean public TradeItemWriter tradeItemWriter() { TradeItemWriter itemWriter = new TradeItemWriter(); itemWriter.setDelegate(flatFileItemWriter(null)); return itemWriter; } @Bean public FlatFileItemWriter flatFileItemWriter(Resource outputResource) { return new FlatFileItemWriterBuilder() .name("itemWriter") .resource(outputResource) .lineAggregator(lineAggregator()) .footerCallback(tradeItemWriter()) .build(); } ``` ```xml ``` -------------------------------- ### Define TaskletAdapter in XML Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/tasklet.adoc Provides an example of configuring a TaskletAdapter in XML, specifying the target object and method to adapt an existing class to the Tasklet interface. ```xml ``` -------------------------------- ### Configure Remote Chunking Job Step with Java and XML Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/spring-batch-integration/sub-elements.adoc Demonstrates how to define a Spring Batch job step that uses remote chunking. The Java example builds a job with a step that processes chunks of items, while the XML example shows the equivalent configuration. Remote chunking enables processing chunks on external systems for scalability. ```java public Job chunkJob(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new JobBuilder(\"personJob\", jobRepository) .start(new StepBuilder(\"step1\", jobRepository) .chunk(200, transactionManager) .reader(itemReader()) .writer(itemWriter()) .build()) .build(); } ``` ```xml ... ``` -------------------------------- ### Show sample XML input for CustomerCredit data Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/xml/README.md Provides an example XML document that represents a list of customers with credit values. This file is used as input for the Spring Batch job that copies CustomerCredit data. The XML is processed by XStream through Spring OXM marshallers. ```xml customer1 10 customer2 20 customer3 30 customer4 40 customer5 50 ``` -------------------------------- ### Initialize FlatFileItemReader Resource (Java) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/readers-and-writers/flat-files/file-item-reader.adoc Demonstrates how to initialize a Resource for the FlatFileItemReader, pointing to a file system resource. This is a basic setup for specifying the input file. ```java Resource resource = new FileSystemResource("resources/trades.csv"); ``` -------------------------------- ### Chaining ItemProcessors (Java) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/processor.adoc This demonstrates chaining multiple ItemProcessors together to perform a more complex transformation sequence, in this example transforming Foo to Bar to Foobar. ```java public class Foo { } ``` ```java public class Bar { public Bar(Foo foo) {} } ``` ```java public class Foobar { public Foobar(Bar bar) {} } ``` ```java public class FooProcessor implements ItemProcessor<Foo, Bar> { public Bar process(Foo foo) throws Exception { //Perform simple transformation, convert a Foo to a Bar return new Bar(foo); } } ``` ```java public class BarProcessor implements ItemProcessor<Bar, Foobar> { public Foobar process(Bar bar) throws Exception { return new Foobar(bar); } } ``` -------------------------------- ### Batch Execution Plan: Stateless Retry Example Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/transaction-appendix.adoc Illustrates a typical batch execution plan featuring a stateless RETRY block with a RECOVER path. This plan highlights the transactional structure and the conditions under which recovery is not supported. ```text 0 | REPEAT(until=exhausted) { 1 | TX { 2 | REPEAT(size=5) { 3 | RETRY(stateless) { 4 | TX { 4.1 | input; 4.2 | database access; | } 5 | } RECOVER { 5.1 | skip; | } | | | } | } | | | } ``` -------------------------------- ### Extended Job Parameter Notation Example Source: https://github.com/spring-projects/spring-batch/wiki/Spring-Batch-5.0-Migration-Guide Demonstrates the extended notation for Spring Batch job parameters, which uses a JSON structure to define the parameter's value, type, and identifying status. This is useful for parameter values containing special characters like commas. The JsonJobParametersConverter supports this format. ```text parameterName='{"value": "parameterValue", "type":"parameterType", "identifying": "booleanValue"}' ``` -------------------------------- ### Pattern Matching Sample Input in Java Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/README.md Demonstrates handling complex file input formats where records span multiple lines and include nested data. This sample processes records starting with HEA, BCU, BAD, BIN, LIT, SIN, and FOT. ```text HEA;0013100345;2007-02-15 NCU;Smith;Peter;;T;20014539;F BAD;;Oak Street 31/A;;Small Town;00235;IL;US SAD;Smith, Elizabeth;Elm Street 17;;Some City;30011;FL;United States BIN;VISA;VISA-12345678903 LIT;1044391041;37.49;0;0;4.99;2.99;1;45.47 LIT;2134776319;221.99;5;0;7.99;2.99;1;221.87 SIN;UPS;EXP;DELIVER ONLY ON WEEKDAYS FOT;2;2;267.34 HEA;0013100346;2007-02-15 BCU;Acme Factory of England;72155919;T BAD;;St. Andrews Road 31;;London;55342;;UK BIN;AMEX;AMEX-72345678903 LIT;1044319101;1070.50;5;0;7.99;2.99;12;12335.46 LIT;2134727219;21.79;5;0;7.99;2.99;12;380.17 LIT;1044339301;79.95;0;5.5;4.99;2.99;4;329.72 LIT;2134747319;55.29;10;0;7.99;2.99;6;364.45 LIT;1044359501;339.99;10;0;7.99;2.99;2;633.94 SIN;FEDX;AMS; FOT;5;36;14043.74 ``` -------------------------------- ### Configure Transaction Manager for Tasklet Steps in Spring Batch v5 Source: https://github.com/spring-projects/spring-batch/wiki/Spring-Batch-5.0-Migration-Guide In Spring Batch v5, the transaction manager must be manually configured for tasklet step definitions. This example shows the v5 approach using StepBuilder with explicit transaction manager injection, contrasting with the v4 configuration. ```java // Sample with v4 @Configuration @EnableBatchProcessing public class MyStepConfig { @Autowired private StepBuilderFactory stepBuilderFactory; @Bean public Step myStep() { return this.stepBuilderFactory.get("myStep") .tasklet(..) // or .chunk() .build(); } } ``` ```java // Sample with v5 @Configuration @EnableBatchProcessing public class MyStepConfig { @Bean public Tasklet myTasklet() { return new MyTasklet(); } @Bean public Step myStep(JobRepository jobRepository, Tasklet myTasklet, PlatformTransactionManager transactionManager) { return new StepBuilder("myStep", jobRepository) .tasklet(myTasklet, transactionManager) // or .chunk(chunkSize, transactionManager) .build(); } } ``` -------------------------------- ### Configure FlatFileItemWriter with Header and Footer Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/common-patterns.adoc Illustrates configuring FlatFileItemWriter with custom header and footer callbacks using both Java and XML syntax. The Java configuration uses FlatFileItemWriterBuilder for fluent setup, while XML uses property injection. Both approaches enable writing dynamic headers and footers to flat files. ```java @Bean public FlatFileItemWriter itemWriter(Resource outputResource) { return new FlatFileItemWriterBuilder() .name("itemWriter") .resource(outputResource) .lineAggregator(lineAggregator()) .headerCallback(headerCallback()) .footerCallback(footerCallback()) .build(); } ``` ```xml ``` -------------------------------- ### Query Customer Data with JdbcTemplate in Java Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/readers-and-writers/database.adoc Example showing traditional data retrieval using JdbcTemplate which loads all results into memory. Returns a list of 1000 CustomerCredit objects immediately. Not suitable for very large datasets due to memory constraints. ```java //For simplicity sake, assume a dataSource has already been obtained JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); List customerCredits = jdbcTemplate.query("SELECT ID, NAME, CREDIT from CUSTOMER", new CustomerCreditRowMapper()); ``` -------------------------------- ### Setting Start Limit for Spring Batch Step Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/chunk-oriented-processing/restart.adoc Configures a Spring Batch Step with a start limit to control how many times it can be executed. Useful for steps that invalidate resources requiring manual recovery. Default start limit is Integer.MAX_VALUE. Throws StartLimitExceededException when limit is exceeded. ```java @Bean public Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("step1", jobRepository) .chunk(10).transactionManager(transactionManager) .reader(itemReader()) .writer(itemWriter()) .startLimit(1) .build(); } ``` ```xml ``` -------------------------------- ### Custom ItemReader Example (Basic) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/readers-and-writers/custom.adoc This example demonstrates a simple ItemReader implementation that reads items from a provided list and removes them one by one. It returns null when the list is empty, satisfying the basic requirements of an ItemReader. ```java public class CustomItemReader implements ItemReader { List items; public CustomItemReader(List items) { this.items = items; } public T read() throws Exception, UnexpectedInputException, NonTransientResourceException, ParseException { if (!items.isEmpty()) { return items.remove(0); } return null; } } ``` -------------------------------- ### Java Configuration for Spring Batch Job Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/processor.adoc This example shows how to configure a Spring Batch job in Java, including setting up an ItemReader, an ItemProcessor, and an ItemWriter. ```java @Bean public Job ioSampleJob(JobRepository jobRepository, Step step1) { return new JobBuilder("ioSampleJob", jobRepository) .start(step1) .build(); } @Bean public Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("step1", jobRepository) .<Foo, Bar>chunk(2).transactionManager(transactionManager) .reader(fooReader()) .processor(fooProcessor()) .writer(barWriter()) .build(); } ``` -------------------------------- ### Configure FlatFileItemWriter with Field Extraction and Formatting Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/readers-and-writers/flat-files/file-item-writer.adoc Demonstrates how to configure FlatFileItemWriter using BeanWrapperFieldExtractor and FormatterLineAggregator for writing CustomerCredit objects. Shows Java-based configuration with explicit field mapping and formatting setup. ```java BeanWrapperFieldExtractor fieldExtractor = new BeanWrapperFieldExtractor<>(); fieldExtractor.setNames(new String[] {"name", "credit"}); fieldExtractor.afterPropertiesSet(); FormatterLineAggregator lineAggregator = new FormatterLineAggregator<>(); lineAggregator.setFormat("%-9s%-2.0f"); lineAggregator.setFieldExtractor(fieldExtractor); return new FlatFileItemWriterBuilder() .name("customerCreditWriter") .resource(outputResource) .lineAggregator(lineAggregator) .build(); ``` ```xml ``` -------------------------------- ### Configure Spring Batch Step using Java Configuration Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/chunk-oriented-processing/configuring.adoc This Java configuration demonstrates how to define a 'sampleJob' and a 'sampleStep' using Spring Batch builders. It shows the autowiring of JobRepository and PlatformTransactionManager, and the setup of a chunk-oriented step with reader and writer. The ItemProcessor is optional. ```java /** * Note the JobRepository is typically autowired in and not needed to be explicitly * configured */ @Bean public Job sampleJob(JobRepository jobRepository, Step sampleStep) { return new JobBuilder("sampleJob", jobRepository) .start(sampleStep) .build(); } /** * Note the TransactionManager is typically autowired in and not needed to be explicitly * configured */ @Bean public Step sampleStep(JobRepository jobRepository, // <2> PlatformTransactionManager transactionManager) { // <1> return new StepBuilder("sampleStep", jobRepository) .chunk(10).transactionManager(transactionManager) // <3> .reader(itemReader()) .writer(itemWriter()) .build(); } ``` -------------------------------- ### Configure StoredProcedureItemReader with Parameters (Java) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/readers-and-writers/database.adoc This example shows how to configure the StoredProcedureItemReader in Java to work with parameters in a stored procedure. It demonstrates how to declare both input and output parameters and how to set them. ```java import org.springframework.batch.item.database.StoredProcedureItemReader; import javax.sql.DataSource; import org.springframework.context.annotation.Bean; import java.util.ArrayList; import java.util.List; import org.springframework.jdbc.core.SqlParameter; import oracle.jdbc.OracleTypes; import java.sql.Types; @Bean public StoredProcedureItemReader reader(DataSource dataSource) { List parameters = new ArrayList<>(); parameters.add(new SqlOutParameter("newId", OracleTypes.CURSOR)); parameters.add(new SqlParameter("amount", Types.INTEGER)); parameters.add(new SqlParameter("custId", Types.INTEGER)); StoredProcedureItemReader reader = new StoredProcedureItemReader(); reader.setDataSource(dataSource); reader.setProcedureName("spring.cursor_func"); reader.setParameters(parameters); reader.setRefCursorPosition(1); reader.setRowMapper(rowMapper()); reader.setPreparedStatementSetter(parameterSetter()); return reader; } ``` -------------------------------- ### Configure Full Spring XML Application Context with Batch Integration Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/spring-batch-integration/namespace-support.adoc This example demonstrates a complete Spring XML application context configuration for Spring Batch Integration. It includes namespaces for beans, integration, batch, and batch-integration, along with their respective schema locations. ```xml ... ``` -------------------------------- ### Define ChunkOrientedStep using Builder (Java) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/whatsnew.adoc Example of configuring a `ChunkOrientedStep` using its builder pattern. This method simplifies step definition by chaining configuration options. It requires essential components like `JobRepository`, `JdbcTransactionManager`, `ItemReader`, `ItemProcessor`, and `ItemWriter`. ```java import org.springframework.batch.core.Step; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.step.builder.ChunkOrientedStepBuilder; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.support.transaction.JdbcTransactionManager; import org.springframework.context.annotation.Bean; public class BatchConfig { @Bean public Step chunkOrientedStep(JobRepository jobRepository, JdbcTransactionManager transactionManager, ItemReader itemReader, ItemProcessor itemProcessor, ItemWriter itemWriter) { int chunkSize = 100; return new ChunkOrientedStepBuilder(jobRepository, transactionManager, chunkSize) .reader(itemReader) .processor(itemProcessor) .writer(itemWriter) .build(); } } ``` -------------------------------- ### Custom ItemReader Example (Restartable) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/readers-and-writers/custom.adoc This example extends the basic ItemReader to make it restartable by using the ItemStream interface. It stores and retrieves the current index from the ExecutionContext to resume processing from where it left off. ```java public class CustomItemReader implements ItemReader, ItemStream { List items; int currentIndex = 0; private static final String CURRENT_INDEX = "current.index"; public CustomItemReader(List items) { this.items = items; } public T read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException { if (currentIndex < items.size()) { return items.get(currentIndex++); } return null; } public void open(ExecutionContext executionContext) throws ItemStreamException { if (executionContext.containsKey(CURRENT_INDEX)) { currentIndex = new Long(executionContext.getLong(CURRENT_INDEX)).intValue(); } else { currentIndex = 0; } } public void update(ExecutionContext executionContext) throws ItemStreamException { executionContext.putLong(CURRENT_INDEX, new Long(currentIndex).longValue()); } public void close() throws ItemStreamException {} } ``` -------------------------------- ### Custom ItemReader Example (Restartable Test) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/readers-and-writers/custom.adoc Demonstrates the usage of the restartable ItemReader and verifies its ability to resume processing from the correct index after interruption. ```java ExecutionContext executionContext = new ExecutionContext(); ((ItemStream)itemReader).open(executionContext); assertEquals("1", itemReader.read()); ((ItemStream)itemReader).update(executionContext); List items = new ArrayList<>(); items.add("1"); items.add("2"); items.add("3"); itemReader = new CustomItemReader<>(items); ((ItemStream)itemReader).open(executionContext); assertEquals("2", itemReader.read()); ``` -------------------------------- ### JobStep Example (Java) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/controlling-flow.adoc Illustrates the use of a JobStep in Java, allowing for externalized job execution within a larger job. ```java @Bean public Job jobStepJob(JobRepository jobRepository, Step jobStepJobStep1) { return new JobBuilder("jobStepJob", jobRepository) .start(jobStepJobStep1) .build(); } @Bean public Step jobStepJobStep1(JobRepository jobRepository, JobLauncher jobLauncher, Job job, JobParametersExtractor jobParametersExtractor) { return new StepBuilder("jobStepJobStep1", jobRepository) .job(job) .launcher(jobLauncher) .parametersExtractor(jobParametersExtractor) .build(); } @Bean public Job job(JobRepository jobRepository) { return new JobBuilder("job", jobRepository) // ... .build(); } @Bean public DefaultJobParametersExtractor jobParametersExtractor() { DefaultJobParametersExtractor extractor = new DefaultJobParametersExtractor(); extractor.setKeys(new String[]{"input.file"}); return extractor; } ``` -------------------------------- ### Configure JsonFileItemWriter with Jackson Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/readers-and-writers/json-reading-writing.adoc This example shows how to set up a `JsonFileItemWriter` using Jackson for JSON marshalling. It requires a Spring `Resource` for the output file and a `JacksonJsonObjectMarshaller` instance. ```java import org.springframework.batch.item.json.JacksonJsonObjectMarshaller; import org.springframework.batch.item.json.JsonFileItemWriter; import org.springframework.batch.item.json.builder.JsonFileItemWriterBuilder; import org.springframework.core.io.ClassPathResource; // ... assuming Trade class is defined @Bean public JsonFileItemWriter jsonFileItemWriter() { return new JsonFileItemWriterBuilder() .jsonObjectMarshaller(new JacksonJsonObjectMarshaller<>()) .resource(new ClassPathResource("trades.json")) .name("tradeJsonFileItemWriter") .build(); } ``` -------------------------------- ### Add @since Tag to Public API (Java) Source: https://github.com/spring-projects/spring-batch/blob/main/CONTRIBUTING.md Example of using the @since tag in JavaDoc comments for newly added public API types and methods, indicating the version they were introduced. ```java /** * ... * * @author First Last * @since 3.0 * @see ... */ ``` -------------------------------- ### Custom ItemReader Example (Test) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/readers-and-writers/custom.adoc Provides a simple test case for the CustomItemReader to ensure correct read operations and null return when the list is empty. ```java List items = new ArrayList<>(); items.add("1"); items.add("2"); items.add("3"); ItemReader itemReader = new CustomItemReader<>(items); assertEquals("1", itemReader.read()); assertEquals("2", itemReader.read()); assertEquals("3", itemReader.read()); assertNull(itemReader.read()); ``` -------------------------------- ### Update License Header Date Range (Java) Source: https://github.com/spring-projects/spring-batch/blob/main/CONTRIBUTING.md Example illustrating the need to update the year in the Apache license header for modified files to reflect the current year of modification. ```java * Copyright 2002-2011 the original author or authors. ``` ```java * Copyright 2002-2013 the original author or authors. ``` -------------------------------- ### Run Spring Batch XML sample via Maven commands Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/xml/README.md Shows the command‑line steps to execute the XML sample using the Maven wrapper. Includes commands for both XML‑based and Java‑based configuration launches. Useful for quickly testing the job without modifying the project. ```bash $>cd spring-batch-samples # Launch the sample using the XML configuration $>../mvnw -Dtest=XmlFunctionalTests#testLaunchJobWithXmlConfig test # Launch the sample using the Java configuration $>../mvnw -Dtest=XmlFunctionalTests#testLaunchJobWithJavaConfig test ``` -------------------------------- ### Create CUSTOMER Table in SQL Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/readers-and-writers/database.adoc Defines the database schema for a CUSTOMER table with ID, NAME, and CREDIT columns. This table is used in examples to demonstrate cursor-based reading in Spring Batch. Requires a database with SQL support. ```sql CREATE TABLE CUSTOMER ( ID BIGINT IDENTITY PRIMARY KEY, NAME VARCHAR(45), CREDIT FLOAT ); ``` -------------------------------- ### Configuring FlatFileItemReader with Java Builder Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/whatsnew.adoc This example shows the traditional builder pattern to configure a FlatFileItemReader in Java using Spring Batch. It sets resource, delimited format, delimiter, and quote character options step by step. The builder allows for flexible configuration but can be verbose. Note that '...' represents omitted configuration. ```java var reader = new FlatFileItemReaderBuilder() .resource(...) .delimited() .delimiter(",") .quoteCharacter('"') ... .build(); ``` -------------------------------- ### Configure Skip Logic - Java/XML Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/chunk-oriented-processing/configuring-skip.adoc Configures skip logic in Spring Batch to handle specific exceptions gracefully during step execution. The Java example uses SkipPolicy with LimitCheckingExceptionHierarchySkipPolicy, while the XML example uses skip-limit attribute. Both configure a skip limit of 10 and specify FlatFileParseException as skippable. The skip limit applies across all phases (read, process, write) and causes step failure when exceeded. ```Java @Bean public Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager) { int skipLimit = 10; var skippableExceptions = Set.of(FlatFileParseException.class); SkipPolicy skipPolicy = new LimitCheckingExceptionHierarchySkipPolicy(skippableExceptions, skipLimit); return new StepBuilder("step1", jobRepository) .chunk(10).transactionManager(transactionManager) .reader(flatFileItemReader()) .writer(itemWriter()) .faultTolerant() .skipPolicy(skipPolicy) .build(); } ``` ```XML ``` -------------------------------- ### Run Spring Batch Sample from Command Line Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/football/README.md Command-line instructions to run the Spring Batch sample using either XML or Java configuration. Requires Maven and the spring-batch-samples directory. ```bash $>cd spring-batch-samples # Launch the sample using the XML configuration $>../mvnw -Dtest=FootballJobFunctionalTests#testLaunchJobWithXmlConfiguration test # Launch the sample using the Java configuration $>../mvnw -Dtest=FootballJobFunctionalTests#testLaunchJobWithJavaConfiguration test ``` -------------------------------- ### Demonstrate ItemReader Streaming in Java Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/readers-and-writers/database.adoc This Java code example shows how to use an ItemReader to stream customer credit items, counting them in a loop. It requires an ItemReader instance, such as a JdbcCursorItemReader. The code opens the reader, reads items until null, and closes it, outputting a counter. Note that this is a simplified demonstration and does not include error handling or full Spring injection. ```java int counter = 0; ExecutionContext executionContext = new ExecutionContext(); itemReader.open(executionContext); Object customerCredit = new Object(); while(customerCredit != null){ customerCredit = itemReader.read(); counter++; } itemReader.close(); ``` -------------------------------- ### Build and Run Spring Batch Application Source: https://github.com/spring-projects/spring-batch/blob/main/ISSUE_REPORTING.md This command sequence shows how to build a Spring Batch Maven project and execute the main batch job. First, it unzips the project archive and navigates into the project directory. Then, it uses `mvn package exec:java` to compile the project and run the main class specified by `exec.mainClass`. ```shell $>unzip spring-batch-mcve.zip && cd spring-batch-mcve $>mvn package exec:java -Dexec.mainClass=org.springframework.batch.MyBatchJobConfiguration ``` -------------------------------- ### Migrate JDBC Configuration with DefaultBatchConfiguration from v5 to v6 (Java) Source: https://github.com/spring-projects/spring-batch/wiki/Spring-Batch-6.0-Migration-Guide Demonstrates migrating a configuration inheriting from `DefaultBatchConfiguration` from Spring Batch 5 to Spring Batch 6. It utilizes `JdbcDefaultBatchConfiguration` for store-specific JDBC attributes. ```java import org.springframework.batch.core.job.JobBuilder; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.batch.core.configuration.annotation.EnableJdbcJobRepository; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; class MyJobConfiguration extends JdbcDefaultBatchConfiguration { @Bean public Job job(JobRepository jobRepository) { return new JobBuilder("job", jobRepository) // job flow omitted .build(); } @Override protected DataSource getDataSource() { return new MyBatchDataSource(); } } ``` ```java // v5 class MyJobConfiguration extends DefaultBatchConfiguration { @Bean public Job job(JobRepository jobRepository) { return new JobBuilder("job", jobRepository) // job flow omitted .build(); } @Override protected DataSource getDataSource() { return new MyBatchDataSource(); } } ``` -------------------------------- ### Configure Fixed Width File Writing with FlatFileItemWriter (Java) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/readers-and-writers/flat-files/file-item-writer.adoc Illustrates how to configure FlatFileItemWriter for fixed-width file output using Java. This example sets up the writer for the CustomerCredit domain object, implying the use of a FormatterLineAggregator (though not explicitly shown in the provided snippet). ```java @Bean public FlatFileItemWriter itemWriter(Resource outputResource) throws Exception { ``` -------------------------------- ### Configure XStreamMarshaller and StaxEventItemWriter Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/readers-and-writers/xml-reading-writing.adoc Demonstrates two ways to configure an XStreamMarshaller and a StaxEventItemWriter for writing Trade objects. The XML snippet defines the marshaller bean using Spring's XStreamMarshaller, while the Java snippet programmatically sets up the same components, showing required properties and usage. Both examples are useful for Spring Batch developers needing XML output. ```xml ``` ```java FileSystemResource resource = new FileSystemResource(\"data/outputFile.xml\"); Map aliases = new HashMap(); aliases.put(\"trade\",\"org.springframework.batch.samples.domain.trade.Trade\"); aliases.put(\"price\",\"java.math.BigDecimal\"); aliases.put(\"customer\",\"java.lang.String\"); aliases.put(\"isin\",\"java.lang.String\"); aliases.put(\"quantity\",\"java.lang.Long\"); Marshaller marshaller = new XStreamMarshaller(); marshaller.setAliases(aliases); StaxEventItemWriter staxItemWriter = new StaxEventItemWriterBuilder() .name(\"tradesWriter\") .marshaller(marshaller) .resource(resource) .rootTagName(\"trade\") .overwriteOutput(true) .build(); staxItemWriter.afterPropertiesSet(); ExecutionContext executionContext = new ExecutionContext(); staxItemWriter.open(executionContext); Trade trade = new Trade(); trade.setPrice(11.39); trade.setIsin(\"XYZ0001\"); trade.setQuantity(5L); trade.setCustomer(\"Customer1\"); staxItemWriter.write(trade); ``` -------------------------------- ### Migrate JDBC Configuration from v5 to v6 (Java) Source: https://github.com/spring-projects/spring-batch/wiki/Spring-Batch-6.0-Migration-Guide Demonstrates the migration of a JDBC configuration from Spring Batch 5 to Spring Batch 6. It introduces the `@EnableBatchProcessing`, `@EnableJdbcJobRepository` annotations for configuring the job repository. The code shows how to split the configuration into `@EnableBatchProcessing` for common attributes and `@EnableJdbcJobRepository` for store-specific configurations. ```java import org.springframework.batch.core.job.JobBuilder; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.batch.core.configuration.annotation.EnableJdbcJobRepository; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @EnableBatchProcessing(taskExecutorRef = "batchTaskExecutor") @EnableJdbcJobRepository(dataSourceRef = "batchDataSource") class MyJobConfiguration { @Bean public Job job(JobRepository jobRepository) { return new JobBuilder("job", jobRepository) // job flow omitted .build(); } } ``` ```java // v5 @EnableBatchProcessing(dataSourceRef = "batchDataSource", taskExecutorRef = "batchTaskExecutor") class MyJobConfiguration { @Bean public Job job(JobRepository jobRepository) { return new JobBuilder("job", jobRepository) // job flow omitted .build(); } } ``` -------------------------------- ### Job Parameter Default Notation Update (Text) Source: https://github.com/spring-projects/spring-batch/wiki/Spring-Batch-5.0-Migration-Guide Shows the evolution of job parameter notation from v4 to v5. V4 used a restrictive format, while v5 offers a more flexible format allowing a fully qualified type name and identification flag. ```text # v4 Notation [+|-]parameterName(parameterType)=value # v5 Notation parameterName=parameterValue,parameterType,identificationFlag ``` -------------------------------- ### Define Split Element with Flows (XML) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/controlling-flow.adoc This example demonstrates defining a split element in XML that contains multiple flow elements. Each flow element then defines steps within the split. ```xml ``` -------------------------------- ### Implement Custom ItemWriter with Java Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/readers-and-writers/custom.adoc Implementation of a custom ItemWriter for Spring Batch that writes items to a transactional list. The writer implements Spring Batch's ItemWriter interface and supports getting the output list. This example uses TransactionAwareProxyFactory to create a transactional list for thread-safe operations. ```java public class CustomItemWriter implements ItemWriter { List output = TransactionAwareProxyFactory.createTransactionalList(); public void write(Chunk items) throws Exception { output.addAll(items); } public List getOutput() { return output; } } ``` -------------------------------- ### Handle Job Execution Status in Java Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/job/configuring-job.adoc Provides a Java code example for the `afterJob` method, showing how to check the status of a JobExecution to determine if the job completed successfully or failed. This is crucial for conditional logic after job runs. ```java public void afterJob(JobExecution jobExecution){ if (jobExecution.getStatus() == BatchStatus.COMPLETED ) { //job success } else if (jobExecution.getStatus() == BatchStatus.FAILED) { //job failure } } ``` -------------------------------- ### Job Scope Binding in XML Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/late-binding.adoc Provides examples of configuring job-scoped beans in XML, enabling late binding to job parameters and execution context. ```xml ``` ```xml ``` -------------------------------- ### Programmatic Spring Batch Configuration with DefaultBatchConfiguration (Java) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/job/configuring-infrastructure.adoc This Java code snippet illustrates programmatic configuration of Spring Batch infrastructure by extending the DefaultBatchConfiguration class. This approach provides the same beans as @EnableBatchProcessing and allows for customization by overriding setter methods. The example includes defining a Spring Batch Job. ```java @Configuration class MyJobConfiguration extends DefaultBatchConfiguration { @Bean public Job job(JobRepository jobRepository) { return new JobBuilder("myJob", jobRepository) // define job flow as needed .build(); } } ```