### Start monitoring stack for metrics sample Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/README.md Changes to the metrics sample directory and starts the Docker Compose stack for Prometheus, push gateway, and Grafana. ```bash $>cd spring-batch-samples/src/main/resources/org/springframework/batch/samples/metrics $>docker-compose up -d ``` -------------------------------- ### Start the database server with Docker Compose Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/shutdown/README.md Run this command from the top level directory of the project to start the database server of the job repository. ```bash $>docker-compose -f spring-batch-samples/src/main/resources/org/springframework/batch/samples/shutdown/docker-compose.yml up -d ``` -------------------------------- ### Chained ItemProcessors example (partial) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/processor.adoc Shows the beginning of a chained ItemProcessor example where Foo is transformed to Bar and then to Foobar. The code is incomplete as displayed. ```java public class Foo {} public class Bar { public Bar(Foo foo) {} } public class Foobar { public Foobar(Bar bar) {} } public class FooProcessor implements ItemProcessor { public Bar process(Foo foo) throws Exception { //Perform simple transformation, convert a Foo to a Bar return new Bar(foo); } } ``` -------------------------------- ### Start shared job repository database for remote step sample Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/README.md Changes to the remote step sample directory and starts the Docker Compose stack for the shared database. ```bash $>cd spring-batch-samples/src/main/resources/org/springframework/batch/samples/remotestep $>docker-compose up -d ``` -------------------------------- ### Start MongoDB server for MongoDB sample Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/README.md Runs a MongoDB container on localhost:27017 for the MongoDB sample. ```bash $>docker run --name mongodb --rm -d -p 27017:27017 mongo ``` -------------------------------- ### Programmatic Setup of 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 the programmatic setup of StaxEventItemWriter with XStreamMarshaller, including resource, root tag, and overwrite settings. It also shows how to open the writer and write a Trade object. ```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); ``` -------------------------------- ### Multiline input file example Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/README.md Sample input file with multiline records, each starting with a header (HEA) and containing nested records (NCU, BAD, SAD, BIN, LIT, SIN, 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 ``` -------------------------------- ### Create parent-child contexts and start jobs with JobOperator Source: https://github.com/spring-projects/spring-batch/wiki/Spring-Batch-6.0-Migration-Guide Shows how to create a base context with CommonBatchConfiguration, then child contexts for FooJobConfiguration and BarJobConfiguration, and start each job using JobOperator. ```java ApplicationContext baseContext = new AnnotationConfigApplicationContext(CommonBatchConfiguration.class); JobOperator jobOperator = baseContext.getBean(JobOperator.class); AnnotationConfigApplicationContext fooContext = new AnnotationConfigApplicationContext(FooJobConfiguration.class); fooContext.setParent(baseContext); Job fooJob = fooContext.getBean(Job.class); jobOperator.start(fooJob, new JobParameters()); AnnotationConfigApplicationContext barContext = new AnnotationConfigApplicationContext(BarJobConfiguration.class); barContext.setParent(baseContext); Job barJob = barContext.getBean(Job.class); jobOperator.start(barJob, new JobParameters()); ``` -------------------------------- ### XML Configuration: Format Property Example 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 Shows the format property in XML configuration. ```xml ``` -------------------------------- ### Multi-line record input example Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/common-patterns.adoc Sample input file for a multi-line record. The record starts with 'HEA' and ends with 'FOT'. ```text HEA;0013100345;2007-02-15 NCU;Smith;Peter;;T;20014539;F BAD;;Oak Street 31/A;;Small Town;00235;IL;US FOT;2;2;267.34 ``` -------------------------------- ### Set Start Limit with startLimit(1) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/chunk-oriented-processing/restart.adoc Configures a Step to run only once by setting start-limit to 1. Attempting to run it again throws StartLimitExceededException. The default start-limit is Integer.MAX_VALUE. ```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 ``` -------------------------------- ### Java configuration for FlatFileItemWriter 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 Java configuration example using FlatFileItemWriterBuilder to create a writer with a resource and PassThroughLineAggregator. ```java @Bean public FlatFileItemWriter itemWriter() { return new FlatFileItemWriterBuilder() .name("itemWriter") .resource(new FileSystemResource("target/test-outputs/output.txt")) .lineAggregator(new PassThroughLineAggregator<>()) .build(); } ``` -------------------------------- ### Sample delimited file with football players 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 Example flat file content with comma-separated fields: ID, lastName, firstName, position, birthYear, debutYear. Used in the simple delimited file reading example. ```text ID,lastName,firstName,position,birthYear,debutYear "AbduKa00,Abdul-Jabbar,Karim,rb,1974,1996", "AbduRa00,Abdullah,Rabih,rb,1975,1999", "AberWa00,Abercrombie,Walter,rb,1959,1982", "AbraDa00,Abramowicz,Danny,wr,1945,1967", "AdamBo00,Adams,Bob,te,1946,1969", "AdamCh00,Adams,Charlie,wr,1979,2003" ``` -------------------------------- ### Example fixed-length file content 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 Sample fixed-length file with 4 fields: ISIN (12 chars), Quantity (3), Price (5), Customer (9). ```text UK21341EAH4121131.11customer1 UK21341EAH4221232.11customer2 UK21341EAH4321333.11customer3 UK21341EAH4421434.11customer4 UK21341EAH4521535.11customer5 ``` -------------------------------- ### XML configuration for FlatFileItemWriter 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 XML configuration example for FlatFileItemWriter with resource and PassThroughLineAggregator properties. ```xml ``` -------------------------------- ### Input file example with BEGIN/END delimiters Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multilineaggregate/README.md Shows the structure of the input file with two groups of trades delimited by BEGIN and END lines. The job operates on these groups as List items. ```plaintext BEGIN UK21341EAH4597898.34customer1 UK21341EAH4611218.12customer2 END BEGIN UK21341EAH4724512.78customer2 UK21341EAH4810809.25customer3 UK21341EAH4985423.39customer4 END ``` -------------------------------- ### Pattern Matching Sample - Input File Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/README.md Example input file for the Pattern Matching Sample, demonstrating a complex file input format with multiline records and nested records. ```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;0013100345;2007-02-15 BCU;Acme Factory of England;72155919;T BAD;;St. Andrews Road 31;;London;55342;;UK BIN;AMEX;AMEX-72345678903 LIT;1044391041;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 ``` -------------------------------- ### Java Configuration: Format Property Example 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 Shows the format property usage in Java with FormatterLineAggregator. The ellipsis indicates omitted code. ```java ... FormatterLineAggregator lineAggregator = new FormatterLineAggregator<>(); lineAggregator.setFormat("%-9s%-2.0f"); ... ``` -------------------------------- ### XML configuration: Simple job step without transitions Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/controlling-flow.adoc After the step executes, the job ends. This is the XML equivalent of the preceding Java example. No transitions are defined. ```xml ``` -------------------------------- ### Example linear commit history output Source: https://github.com/spring-projects/spring-batch/blob/main/CONTRIBUTING.md Sample output from the git log command showing a linear commit history. Use this as a reference to verify your own history is linear. ```text * e1f6de38e04a5227fea2d4dfa1935b50beaf2d00 GH-2002: Initial support for complex conditional replacements * 65d2df652abaae2ca309d96e3026c2d67312655f Add ability to set a custom TaskExecutor impl, remove unused namespaces from JSR bootst * 85807568575c24d8878ad605a344f2bc35bb2b13 Update to allow restart parameters to override parameters in JSR JobOperator an * a21df75ce9dfc92e9768353bda8274248aefe425 GH-2049: Support multiple fragmentRootElementNames in StaxEventItemReader * 7f1130c9a265a3ce18a46cbbc122e6573167a036 Fix TCK test JobOperatorTests.testJobOperatorRestartJobAlreadyAbandoned * c4231c4cc861bbcc43437c80a03ddd9b7b2897a3 Fixed no executions returned check and added a unit test ``` -------------------------------- ### Start a Step by Name with JobOperatorTestUtils.startStep Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/testing.adoc Use the startStep method to run a specific step by name for targeted testing. This is useful when end-to-end tests become unmanageable. ```java JobExecution jobExecution = jobOperatorTestUtils.startStep("loadFileStep"); ``` -------------------------------- ### SQL: Create CUSTOMER table schema Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/readers-and-writers/database.adoc Defines the CUSTOMER table used in the examples. It has three columns: ID (identity primary key), NAME, and CREDIT (float). ```sql CREATE TABLE CUSTOMER ( ID BIGINT IDENTITY PRIMARY KEY, NAME VARCHAR(45), CREDIT FLOAT ); ``` -------------------------------- ### XML Configuration for a Restartable Job Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/chunk-oriented-processing/restart.adoc This XML configuration defines a job with three steps. The playerload step has no restart configuration, so it runs only once. The gameLoad step has allow-start-if-complete set to true, so it runs every time. The playerSummarization step has start-limit set to 2, so it can only start twice. ```xml ``` -------------------------------- ### CommandLineJobOperator start with date parameter Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/job/running.adoc Launches a job from the command line using CommandLineJobOperator, passing a date as a job parameter. The parameter is in the format name=value,type,identifying. ```bash ``` -------------------------------- ### Java: JdbcTemplate query example Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/readers-and-writers/database.adoc Shows how to use JdbcTemplate to query all rows from CUSTOMER table and map them to CustomerCredit objects. It returns a list containing all 1000 rows (assuming the table has 1000 rows). ```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()); ``` -------------------------------- ### Foo to Bar transformation with ItemProcessor Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/processor.adoc Shows a complete transformation example: Foo, Bar, FooProcessor implementing ItemProcessor, and BarWriter. The processor converts a Foo to a Bar, and the writer expects Bar objects. ```java public class Foo {} public class Bar { public Bar(Foo foo) {} } public class FooProcessor implements ItemProcessor { public Bar process(Foo foo) throws Exception { //Perform simple transformation, convert a Foo to a Bar return new Bar(foo); } } public class BarWriter implements ItemWriter { public void write(Chunk bars) throws Exception { //write bars } } ``` -------------------------------- ### Run the MultiLine sample Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multiline/README.md Commands to run the sample from the command line. Use the XML configuration with testLaunchJobWithXmlConfig or the Java configuration with testLaunchJobWithJavaConfig. ```bash $>cd spring-batch-samples # Launch the sample using the XML configuration $>../mvnw -Dtest=MultiLineFunctionalTests#testLaunchJobWithXmlConfig test # Launch the sample using the Java configuration $>../mvnw -Dtest=MultiLineFunctionalTests#testLaunchJobWithJavaConfig test ``` -------------------------------- ### Run the Hello World sample from the command line Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/helloworld/README.md Run the sample from the command line using Maven. The command changes to the spring-batch-samples directory and executes the Maven wrapper with the test goal, specifying the test class and method. ```shell $>cd spring-batch-samples $>../mvnw -Dtest=HelloWorldJobFunctionalTests#testLaunchJob test ``` -------------------------------- ### Run the sample from the command line Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/adapter/tasklet/README.md Use this command to run the TaskletAdapterJobFunctionalTests test. It executes the testLaunchJob test method. ```bash $>cd spring-batch-samples $>../mvnw -Dtest=TaskletAdapterJobFunctionalTests#testLaunchJob test ``` -------------------------------- ### Run a sample from the command line Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/README.md Use these commands to run a sample job from the command line. Replace [JobName] with the actual job name, e.g., HelloWorld. ```bash $>cd spring-batch-samples $>../mvnw -Dtest=[JobName]FunctionalTests#test[JobName] test ``` -------------------------------- ### Git commit author example (incorrect) Source: https://github.com/spring-projects/spring-batch/blob/main/CONTRIBUTING.md Example of an unacceptable git commit author format, showing a nickname instead of a real name. ```text Author: Nickname ``` -------------------------------- ### Fully configured Spring XML application context for Spring 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 shows a complete Spring XML application context file for Spring Batch Integration, including the integration, batch, and batch-integration namespaces with their schema locations. It serves as a template for a full configuration. ```xml ... ``` -------------------------------- ### Run the sample with Maven Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multirecordtype/README.md Commands to run the sample from the command line, using either the XML or Java configuration. ```bash $>cd spring-batch-samples # Launch the sample using the XML configuration $>../mvnw -Dtest=MultiRecordTypeFunctionalTests#testLaunchJobWithXmlConfig test # Launch the sample using the Java configuration $>../mvnw -Dtest=MultiRecordTypeFunctionalTests#testLaunchJobWithJavaConfig test ``` -------------------------------- ### Java Configuration: Handling different exit codes Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/controlling-flow.adoc Java configuration example showing how to work with a different exit code. It defines a job with three possibilities: if step1 fails, the job ends; if it completes with skips, it goes to errorPrint1; otherwise it goes to step2. ```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(); } ``` -------------------------------- ### Git commit author example (correct) Source: https://github.com/spring-projects/spring-batch/blob/main/CONTRIBUTING.md Example of an acceptable git commit author format, using the contributor's real first and last name. ```text Author: First Last ``` -------------------------------- ### Run sample with XML configuration Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/fixed/README.md Command to launch the sample using the XML configuration. Run from the spring-batch-samples directory. ```bash $>cd spring-batch-samples # Launch the sample using the XML configuration $>../mvnw -Dtest=FixedLengthFunctionalTests#testLaunchJobWithXmlConfig test ``` -------------------------------- ### XML Configuration: next element for conditional flow Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/controlling-flow.adoc XML configuration example showing the next element to transition to stepB when the exit status is FAILED. The on attribute uses a simple pattern-matching scheme to match the ExitStatus. ```xml ``` -------------------------------- ### Define a Job with the Element in XML Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/domain.adoc XML configuration example for defining a Job using the batch namespace's element. It declares three steps with the next attribute to chain them. ```xml ``` -------------------------------- ### Run sample with Java configuration Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/fixed/README.md Command to launch the sample using the Java configuration. Run from the spring-batch-samples directory. ```bash $>cd spring-batch-samples # Launch the sample using the Java configuration $>../mvnw -Dtest=FixedLengthFunctionalTests#testLaunchJobWithJavaConfig test ``` -------------------------------- ### Run football sample with Maven Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/football/README.md Commands to launch the football sample using Maven. Use the XML configuration command or the Java configuration command. ```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 ``` -------------------------------- ### Multi-line input file format Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multiline/README.md Example of a multi-line input file where each logical item spans multiple physical lines. The pattern uses BEGIN and END markers to delimit each item, with INFO and AMNT lines in between. ```text BEGIN INFO,UK21341EAH45,customer1 AMNT,978,98.34 END BEGIN INFO,UK21341EAH46,customer2 AMNT,112,18.12 END ... ``` -------------------------------- ### Configure TaskExecutorJobOperator with JobRepository Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/job/configuring-operator.adoc Configures a TaskExecutorJobOperator with only a JobRepository dependency using the JobOperatorFactoryBean. The Java example uses a @Bean method, while the XML example defines a bean with the jobRepository property. All other dependencies are optional. ```java @Bean public JobOperatorFactoryBean jobOperator(JobRepository jobRepository) { JobOperatorFactoryBean jobOperatorFactoryBean = new JobOperatorFactoryBean(); jobOperatorFactoryBean.setJobRepository(jobRepository); return jobOperatorFactoryBean; } ``` ```xml ``` -------------------------------- ### footballJob.xml steps list Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/football/README.md XML configuration snippet from footballJob.xml showing the list of steps in the job: playerload, gameLoad, and playerSummarization. ```xml ``` -------------------------------- ### Configure TaskExecutorJobOperator with TaskExecutor Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/job/configuring-operator.adoc Configures a TaskExecutorJobOperator to return immediately by setting a TaskExecutor. The Java example uses SimpleAsyncTaskExecutor, and the XML example defines a nested bean for the taskExecutor property. Any implementation of the Spring TaskExecutor interface can be used to control asynchronous execution. ```java @Bean public JobOperatorFactoryBean jobOperator(JobRepository jobRepository) { JobOperatorFactoryBean jobOperatorFactoryBean = new JobOperatorFactoryBean(); jobOperatorFactoryBean.setJobRepository(jobRepository); jobOperatorFactoryBean.setTaskExecutor(new SimpleAsyncTaskExecutor()); return jobOperatorFactoryBean; } ``` ```xml ``` -------------------------------- ### Unit test NoWorkFoundStepExecutionListener using MetaDataInstanceFactory.createStepExecution() Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/testing.adoc Uses the Spring Batch test module's MetaDataInstanceFactory to create a StepExecution more concisely, avoiding the verbose setup. Still sets exit status and read count, then asserts the afterStep method returns FAILED. ```java private NoWorkFoundStepExecutionListener tested = new NoWorkFoundStepExecutionListener(); @Test public void testAfterStep() { StepExecution stepExecution = MetaDataInstanceFactory.createStepExecution(); stepExecution.setExitStatus(ExitStatus.COMPLETED); stepExecution.setReadCount(0); ExitStatus exitStatus = tested.afterStep(stepExecution); assertEquals(ExitStatus.FAILED.getExitCode(), exitStatus.getExitCode()); } ``` -------------------------------- ### Configure a Poller for the Job-Launching Gateway (Java and XML) Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/spring-batch-integration/available-attributes-of-the-job-launching-gateway.adoc Shows how to configure a poller for the JobLaunchingGateway when it receives messages from a PollableChannel. The Java example uses @ServiceActivator with a @Poller annotation, while the XML example uses the sub-element. Both set a fixed-rate of 1000 milliseconds. ```java @Bean @ServiceActivator(inputChannel = "queueChannel", poller = @Poller(fixedRate="1000")) public JobLaunchingGateway sampleJobLaunchingGateway() { JobLaunchingGateway jobLaunchingGateway = new JobLaunchingGateway(jobLauncher()); jobLaunchingGateway.setOutputChannel(replyChannel()); return jobLaunchingGateway; } ``` ```xml ``` -------------------------------- ### Run the sample with Maven Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/xml/README.md Commands to run the sample from the command line. First navigate to the spring-batch-samples directory, then launch the sample using either the XML configuration or the Java configuration via Maven. ```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 ``` -------------------------------- ### Run the sample with Maven Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/README.md Command to run the Pattern Matching sample from the command line using Maven's test goal. ```bash $>cd spring-batch-samples $>../mvnw -Dtest=PatternMatchingJobFunctionalTests#testJobLaunch test ``` -------------------------------- ### Run the Restart sample with Maven Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/restart/fail/README.md Run the sample from the command line. The command changes to the spring-batch-samples directory and executes the Maven wrapper with the test parameter RestartFunctionalTests#testLaunchJob. ```bash $>cd spring-batch-samples $>../mvnw -Dtest=RestartFunctionalTests#testLaunchJob test ``` -------------------------------- ### Batch Namespace XML Configuration Example Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/domain.adoc Shows how to configure a Spring Batch job using the batch XML namespace. The example defines a job with a step that uses a chunk-based tasklet with an item reader, writer, and commit interval. Note: The batch XML namespace is deprecated as of Spring Batch 6.0 and will be removed in version 7.0. ```xml ``` -------------------------------- ### Run MultiResource sample with Maven Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multiresource/README.md Commands to run the sample from the command line. First change to the spring-batch-samples directory, then launch the sample using either the XML configuration or the Java configuration by specifying the corresponding test method. ```bash $>cd spring-batch-samples # Launch the sample using the XML configuration $>../mvnw -Dtest=MultiResourceFunctionalTests#testLaunchJobWithXmlConfig test # Launch the sample using the Java configuration $>../mvnw -Dtest=MultiResourceFunctionalTests#testLaunchJobWithJavaConfig test ``` -------------------------------- ### Run sample tests with Maven Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/adapter/readerwriter/README.md Executes the DelegatingJobFunctionalTests test method testLaunchJob from the command line after changing into the spring-batch-samples directory. Requires Maven wrapper (../mvnw). ```bash $>cd spring-batch-samples $>../mvnw -Dtest=DelegatingJobFunctionalTests#testLaunchJob test ``` -------------------------------- ### Get the process id from logs Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/shutdown/README.md The process id is printed in the first line of logs and is needed for the stop step. ```text Process id = 73280 ``` -------------------------------- ### JobExecutionDecider Implementation Example Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/controlling-flow.adoc Implements JobExecutionDecider to make a flow decision based on a condition, returning a FlowExecutionStatus of 'FAILED' or 'COMPLETED'. ```java public class MyDecider implements JobExecutionDecider { public FlowExecutionStatus decide(JobExecution jobExecution, StepExecution stepExecution) { String status; if (someCondition()) { status = "FAILED"; } else { status = "COMPLETED"; } return new FlowExecutionStatus(status); } } ``` -------------------------------- ### Run RepositoryItemReader/RepositoryItemWriter sample commands Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/jpa/README.md Commands to run the RepositoryItemReader/RepositoryItemWriter sample using either XML or Java configuration. The commands execute Maven tests with the Maven wrapper. ```bash $>cd spring-batch-samples # Launch the sample using the XML configuration $>../mvnw -Dtest=RepositoryFunctionalTests#testLaunchJobWithXmlConfig test # Launch the sample using the Java configuration $>../mvnw -Dtest=RepositoryFunctionalTests#testLaunchJobWithJavaConfig test ``` -------------------------------- ### Java Configuration: FormattedBuilder Example 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 Uses FlatFileItemWriterBuilder.FormattedBuilder to automatically create BeanWrapperFieldExtractor and FormatterLineAggregator. Sets format and names directly. ```java @Bean public FlatFileItemWriter itemWriter(Resource outputResource) throws Exception { return new FlatFileItemWriterBuilder() .name("customerCreditWriter") .resource(outputResource) .formatted() .format("%-9s%-2.0f") .names(new String[] {"name", "credit"}) .build(); } ``` -------------------------------- ### Command to run the sample Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multilineaggregate/README.md Run the sample from the command line using Maven. The command changes to the spring-batch-samples directory and executes the specific test. ```bash $>cd spring-batch-samples $>../mvnw -Dtest=MultilineAggregateJobFunctionalTests#testJobLaunch test ``` -------------------------------- ### Configure FixedLengthTokenizer with ranges in 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 Java configuration for FixedLengthLineTokenizer, defining ranges for each field length. The example is incomplete in the source. ```java @Bean public FixedLengthTokenizer fixedLengthTokenizer() { FixedLengthTokenizer tokenizer = new FixedLengthTokenizer(); ``` -------------------------------- ### CompositeItemProcessor chaining example Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/processor.adoc Chains a FooProcessor and a BarProcessor into a CompositeItemProcessor that produces a Foobar. The delegates are set as a list of item processors. ```java CompositeItemProcessor compositeProcessor = new CompositeItemProcessor(); List itemProcessors = new ArrayList(); itemProcessors.add(new FooProcessor()); itemProcessors.add(new BarProcessor()); compositeProcessor.setDelegates(itemProcessors); ``` -------------------------------- ### Java Configuration - on() method Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/step/controlling-flow.adoc Shows how to define conditional transitions using the on() method in Java configuration. ```APIDOC ## Java Configuration - on() method ### Description Defines conditional transitions using the `on()` method. The pattern matches the ExitStatus of the step. ### Configuration ```java ... .from(stepA).on("FAILED").to(stepB) ... ``` ### Parameters - **pattern** (string) - Required - Pattern to match against the ExitStatus. Supports `*` (zero or more characters) and `?` (exactly one character). - **to** (Step) - Required - The next step to execute. ### Behavior - The `on()` method references the exit code of the ExitStatus. - If the ExitStatus is not covered by any transition, the framework throws an exception and the Job fails. - Transitions are automatically ordered from most specific to least specific. ``` -------------------------------- ### Configure StepScopeTestExecutionListener with @SpringBatchTest Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/testing.adoc Starting from v4.1, @SpringBatchTest imports StepScopeTestExecutionListener and JobScopeTestExecutionListener automatically, so the test class only needs @SpringBatchTest and @SpringJUnitConfig. ```java @SpringBatchTest @SpringJUnitConfig public class StepScopeTestExecutionListenerIntegrationTests { // This component is defined step-scoped, so it cannot be injected unless // a step is active... @Autowired private ItemReader reader; public StepExecution getStepExecution() { StepExecution execution = MetaDataInstanceFactory.createStepExecution(); execution.getExecutionContext().putString("input.data", "foo,bar,spam"); return execution; } @Test public void testReader() { // The reader is initialized and bound to the input data assertNotNull(reader.read()); } } ``` -------------------------------- ### Run the sample with Maven Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/json/README.md Command-line instructions to run the JsonFunctionalTests test. Navigate to the spring-batch-samples directory and execute the Maven wrapper with the test property. ```bash $>cd spring-batch-samples $>../mvnw -Dtest=JsonFunctionalTests#testJsonReadingAndWriting test ``` -------------------------------- ### Mock Domain Objects with StepExecutionListener Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/testing.adoc Example of a StepExecutionListener that returns ExitStatus.FAILED when no work is found, useful for testing domain object mocking. ```java public class NoWorkFoundStepExecutionListener implements StepExecutionListener { public ExitStatus afterStep(StepExecution stepExecution) { if (stepExecution.getReadCount() == 0) { return ExitStatus.FAILED; } return null; } } ``` -------------------------------- ### Person class with Bean Validation annotations Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/processor.adoc Example of a Person class annotated with @NotEmpty from the Bean Validation API (JSR-303). This is used with BeanValidatingItemProcessor. ```java class Person { @NotEmpty private String name; public Person(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` -------------------------------- ### PageableItemReaderBuilder example Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/whatsnew.adoc Compares RepositoryItemReaderBuilder with the new PageableItemReaderBuilder, which takes a function from Pageable to Slice for compile-time safety. ```java // before RepositoryItemReader reader = new RepositoryItemReaderBuilder() .repository(customerRepository) .methodName("findAll") .sort(Sort.by(Sort.Direction.ASC, "id")) .pageSize(100) .name("customerReader") .build(); // after PageableItemReader reader = new PageableItemReaderBuilder() .query(customerRepository::findAll) .sort(Sort.by(Sort.Direction.ASC, "id")) .pageSize(100) .name("customerReader") .build(); ``` -------------------------------- ### Command line to run the sample Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/processindicator/README.md Run the sample from the command line using Maven. The command changes to the spring-batch-samples directory and executes the ProcessIndicatorJobFunctionalTests test. ```bash $>cd spring-batch-samples $>../mvnw -Dtest=ProcessIndicatorJobFunctionalTests#testLaunchJob test ``` -------------------------------- ### CustomerCredit domain class for delimited writing 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 A simple domain object used in the delimited file writing example. Getters and setters are omitted for clarity. ```java public class CustomerCredit { private int id; private String name; private BigDecimal credit; //getters and setters removed for clarity } ``` -------------------------------- ### Run JdbcCursorFunctionalTests with Maven Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/jdbc/README.md Run the cursor reader sample from the command line. The first command changes to the spring-batch-samples directory, then the Maven wrapper runs the JdbcCursorFunctionalTests with either the XML or Java configuration. ```bash $>cd spring-batch-samples # Launch the sample using the XML configuration $>../mvnw -Dtest=JdbcCursorFunctionalTests#testLaunchJobWithXmlConfig test # Launch the sample using the Java configuration $>../mvnw -Dtest=JdbcCursorFunctionalTests#testLaunchJobWithJavaConfig test ``` -------------------------------- ### Javadoc @since tag example Source: https://github.com/spring-projects/spring-batch/blob/main/CONTRIBUTING.md Use this Javadoc format for newly-added public API types and methods, including the @since tag with the version number. ```java /** * ... * * @author First Last * @since 3.0 * @see ... */ ``` -------------------------------- ### Show configured remotes Source: https://github.com/spring-projects/spring-batch/blob/main/CONTRIBUTING.md Displays the remote repositories configured for the local clone. ```bash git remote show ``` -------------------------------- ### BarProcessor and FoobarWriter implementations Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/processor.adoc Defines a BarProcessor that converts a Bar to a Foobar and a FoobarWriter that writes a chunk of Foobar items. These are used as delegates in a CompositeItemProcessor example. ```java public class BarProcessor implements ItemProcessor { public Foobar process(Bar bar) throws Exception { return new Foobar(bar); } } public class FoobarWriter implements ItemWriter{ public void write(Chunk items) throws Exception { //write items } } ``` -------------------------------- ### Run StartJobExecutionApp from the command line Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/shutdown/README.md Run the application from the command line using Maven. The process id from the first line of logs is needed for the stop step. ```bash ./mvnw -pl org.springframework.batch:spring-batch-samples exec:java -Dexec.mainClass=org.springframework.batch.samples.shutdown.StartJobExecutionApp ``` -------------------------------- ### Sample fixed-length records Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/fixed/README.md Example of the fixed-length record format used in the sample. Each record contains a name (characters 1-9) and a credit value (characters 10-11). ```text customer110 customer220 customer330 customer440 customer550 customer660 ``` -------------------------------- ### Run JdbcPagingFunctionalTests with Maven Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/jdbc/README.md Run the paging reader sample from the command line. The first command changes to the spring-batch-samples directory, then the Maven wrapper runs the JdbcPagingFunctionalTests with either the XML or Java configuration. ```bash $>cd spring-batch-samples # Launch the sample using the XML configuration $>../mvnw -Dtest=JdbcPagingFunctionalTests#testLaunchJobWithXmlConfig test # Launch the sample using the Java configuration $>../mvnw -Dtest=JdbcPagingFunctionalTests#testLaunchJobWithJavaConfig test ``` -------------------------------- ### Tag the release: set version, commit, tag, and prepare next development version Source: https://github.com/spring-projects/spring-batch/wiki/Release-process-for-v5 Run these commands from the project root to set the release version, commit, tag, push, and then set the next development version. The 'v' prefix in the tag name is important. ```bash $./mvnw versions:set -DgenerateBackupPoms=false -DnewVersion=5.2.0-M1 $git commit -a -m "Release version 5.2.0-M1" $git tag -a v5.2.0-M1 -m "Release version 5.2.0-M1" $./mvnw versions:set -DgenerateBackupPoms=false -DnewVersion=5.2.0-SNAPSHOT $git commit -a -m "Next development version" $git push upstream main $git push upstream v5.2.0-M1 ``` -------------------------------- ### Read XML with StaxEventItemReader Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-docs/modules/ROOT/pages/readers-and-writers/xml-reading-writing.adoc Demonstrates programmatic setup of StaxEventItemReader with XStreamMarshaller, setting the resource, fragment root element name, and reading all items in a loop until null. ```java StaxEventItemReader xmlStaxEventItemReader = new StaxEventItemReader<>(); Resource resource = new ByteArrayResource(xmlResource.getBytes()); 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"); XStreamMarshaller unmarshaller = new XStreamMarshaller(); unmarshaller.setAliases(aliases); xmlStaxEventItemReader.setUnmarshaller(unmarshaller); xmlStaxEventItemReader.setResource(resource); xmlStaxEventItemReader.setFragmentRootElementName("trade"); xmlStaxEventItemReader.open(new ExecutionContext()); boolean hasNext = true; Trade trade = null; while (hasNext) { trade = xmlStaxEventItemReader.read(); if (trade == null) { hasNext = false; } else { System.out.println(trade); } } ``` -------------------------------- ### Run MailJobFunctionalTests with Maven Source: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/samples/mail/README.md Run the mail writer sample from the command line. Navigate to the spring-batch-samples directory and execute the Maven wrapper with the test parameter MailJobFunctionalTests#testLaunchJob. ```bash $>cd spring-batch-samples $>../mvnw -Dtest=MailJobFunctionalTests#testLaunchJob test ```