Spring Batch: Sharing Batch Step Configurations
When defining a Spring batch step, often common configurations are added to almost every step. In order to not violate DRY (Don’t Repeat Yourself), a StepBuilder can be customized upstream with all the shared configurations.
Configuring the StepBuilder
@Configuration
public class SharedStepBuilderFactory extends StepBuilderFactory {
@Autowired
public JobRepository jobRepository;
@Autowired
public PlatformTransactionManager transactionManager;
// Inject shared values here and use them as well
@Value
private String logDirectory;
public SharedStepBuilderFactory(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
super(jobRepository, transactionManager);
}
@Override
public StepBuilder get(final String name) {
// Get the default step builder
final StepBuilder builder = super.get(name);
// Add listeners you want for EVERY step
stepBuilder.listener(new StepLoggingListener());
stepBuilder.listener(getCustomLoggingListener(logDirectory);
return stepBuilder;
}
}
Implementation
@Configuration
public class StepConfig {
@Bean
public Step getStepOne(final SharedStepBuilderFactory sharedStepBuilderFactory) {
return sharedStepBuilderFactory
.get("stepOne")
.reader(stepOneReader())
.writer(stepOneWriter())
.build(); // The listeners are already configured for this step from the SharedStepBuilderFactory
}
}