如何在Spring Batch的context.xml中重写JobRepository?
在XML配置场景下覆盖Spring Batch的JobRepository Bean
已知Java配置可通过继承DefaultBatchConfigurer并重写createJobRepository方法覆盖JobRepository Bean,若已在context.xml中定义了如下jobRepository_new Bean,可按以下步骤实现重写:
<bean id="jobRepository_new" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean"> <property name="databaseType" value="Oracle" /> <property name="dataSource" ref="dataSource-batch" /> <property name="transactionManager" ref="transactionManager" /> <property name="tablePrefix" value="BATCH_" /> <property name="lobHandler" ref="oracleLobHandler" /> </bean>
实现步骤
- 自定义BatchConfigurer引用XML中的自定义JobRepository
创建继承DefaultBatchConfigurer的类,重写getJobRepository方法,直接返回XML中定义的jobRepository_new实例:
import org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer; import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class CustomBatchConfigurer extends DefaultBatchConfigurer { private final JobRepository jobRepository; @Autowired public CustomBatchConfigurer(JobRepository jobRepository) { // 父类构造传null,避免自动创建默认JobRepository super(null); this.jobRepository = jobRepository; } @Override public JobRepository getJobRepository() { return this.jobRepository; } }
- 确保配置生效
- 保证
context.xml被Spring上下文加载,jobRepository_newBean能被正常实例化。 - 确保
CustomBatchConfigurer被Spring组件扫描机制捕获(比如所在包被@ComponentScan注解覆盖)。
这样Spring Batch就会使用你在XML中定义的jobRepository_new,替代默认自动创建的JobRepository。
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

