To provide input dynamically in a Spring Batch application, you can use parameters. Parameters can be passed to the batch job when it is launched. Here’s an example extending the previous one to accept the input file path as a parameter:
Step 1: Update Batch Configuration
Update your BatchConfiguration.java
to include a parameter for the input file path:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
@Configuration @EnableBatchProcessing public class BatchConfiguration { @Value("${input.file.path}") // Read input file path from application.properties private String inputFilePath; // Existing beans... @Bean public FlatFileItemReader<MyInputData> reader() { return new FlatFileItemReaderBuilder<MyInputData>() .name("myItemReader") .resource(new FileSystemResource(inputFilePath)) .lineTokenizer(lineTokenizer()) .fieldSetMapper(new BeanWrapperFieldSetMapper<MyInputData>() {{ setTargetType(MyInputData.class); }}) .build(); } // Rest of the configuration remains unchanged... } |
Step 2: Create an application.properties File
Create an application.properties
file in the src/main/resources
directory with the following content:
1 |
input.file.path=src/main/resources/input.csv |
This configuration specifies the default input file path. You can override it when launching the application.
Step 3: Update Main Class
Update your BatchApplication.java
to include a CommandLineRunner
bean that allows you to pass the input file path as a command-line argument:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
@SpringBootApplication public class BatchApplication { @Autowired private JobLauncher jobLauncher; @Autowired private Job myJob; public static void main(String[] args) { SpringApplication.run(BatchApplication.class, args); } @Bean public CommandLineRunner commandLineRunner() { return new CommandLineRunner() { @Override public void run(String... args) throws Exception { if (args.length > 0) { // If an argument is provided, use it as the input file path jobLauncher.run(myJob, new JobParametersBuilder() .addString("input.file.path", args[0]) .toJobParameters()); } else { // Use the default input file path from application.properties jobLauncher.run(myJob, new JobParameters()); } } }; } } |
Step 4: Run the Application with Dynamic Input
Now, you can run your Spring Batch application with a dynamic input file path. If you run the application from the command line, provide the input file path as an argument:
1 |
java -jar your-application.jar /path/to/custom-input.csv |
If no argument is provided, the default input file path specified in application.properties
will be used.
One Comment on “Dynamically Configuring Input in Spring Batch: A Guide to Flexible Batch Processing in Eclipse”