前言:BatchConfigurer作为策略接口提供了自定义SpringBatch基础设施组件能力。在使用@EnableBatchProcessing注解后,即可获取每个SpringBatch基础设施组件实例。
BatchConfigurer接口当程序使用了@EnableBatchProcessing注解时,SpringBatch会执行以下流程。首先通过BatchConfigurer接口的实现来创建这些bean,然后通过SimpleBatchConfigurationt将它们添加到Spring ApplicationContext中。
BatchConfigurer接口方法
BatchConfigurer提供了四个方法,每个方法都是为SpringBatch基础设施提供了一个主要组件。
- JobRepository操作SpringBatch元数据库增删改查
- JobLauncher启动SpringBatch作业入口
- PlatformTransactionManager 为SpringBatch提供所有的事务管理
- JobExplorer提供了针对作业存储库中所保存数据的只读视图
public interface BatchConfigurer {
JobRepository getJobRepository() throws Exception;
PlatformTransactionManager getTransactionManager() throws Exception;
JobLauncher getJobLauncher() throws Exception;
JobExplorer getJobExplorer() throws Exception;
}
自定义BatchConfigurer
如果默认的DefaultBatchConfigurer不满足业务现状需要我们自定义BatchConfigurer。其实我们自定义的BatchConfigurer主要是要从写DefaultBatchConfigurer类里面方法实现。
public class CustomBatchConfigurer extends DefaultBatchConfigurer {
@Resource(name = "respDataSource")
private DataSource dataSource;
@Autowired
private PlatformTransactionManager platformTransactionManager;
@Override
public PlatformTransactionManager getTransactionManager() {
return platformTransactionManager;
}
@Override
protected JobExplorer createJobExplorer() throws Exception {
JobExplorerFactoryBean jobExplorerFactoryBean = new JobExplorerFactoryBean();
jobExplorerFactoryBean.setDataSource(this.dataSource);
jobExplorerFactoryBean.setTablePrefix("ZSL_");
jobExplorerFactoryBean.afterPropertiesSet();
return jobExplorerFactoryBean.getObject();
}
@Override
protected JobLauncher createJobLauncher() throws Exception {
return super.createJobLauncher();
}
@Override
protected JobRepository createJobRepository() throws Exception {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(this.dataSource);
factory.setTablePrefix("ZSL_");
factory.setTransactionManager(platformTransactionManager);
factory.afterPropertiesSet();
return factory.getObject();
}
}
注意:由于JobRepository和JobExplorer使用相同的底层数据存储,因此同时配置它们确保一直。



