Spring 使用 Java Config Beans 定义的 Batch Infrastructure 而不是 @EnableBatchProcessing

Spring Batch Infrastructure defined with Java Config Beans not with @EnableBatchProcessing

我使用 Spring 批次 4.3.2。我需要为 JobLauncher 定义一个 TaskExecutor。因为我不想启用 bean 覆盖,所以使用 DefaultBatchConfigurer 的解决方案不适用。我最终得到了下面的 bean,我自己定义了所有 bean。我的问题:

  1. 除了我的,你还看到其他解决方案吗?
  2. bean 的定义方式是否正确?

感谢您的帮助! 干杯 T

 @Bean
public JobBuilderFactory jobBuilderFactory(JobRepository jobRepository) {
    return new JobBuilderFactory(jobRepository);
}

@Bean
public StepBuilderFactory stepBuilderFactory(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
    return new StepBuilderFactory(jobRepository, transactionManager);
}

@Bean
public JobRegistry jobRegistry() {
    return new MapJobRegistry();
}

@Bean
public JobRepository createJobRepository(DataSource dataSource, PlatformTransactionManager transactionManager) throws Exception {
    JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
    factory.setDataSource(dataSource);
    factory.setTransactionManager(transactionManager);
    factory.afterPropertiesSet();
    return factory.getObject();
}

@Bean
public JobExplorer createJobExplorer(DataSource dataSource) throws Exception {
    JobExplorerFactoryBean jobExplorerFactoryBean = new JobExplorerFactoryBean();
    jobExplorerFactoryBean.setDataSource(dataSource);
    jobExplorerFactoryBean.afterPropertiesSet();
    return jobExplorerFactoryBean.getObject();
}

@Bean
public JobLauncher jobLauncher(ThreadPoolTaskExecutor taskExecutor, JobRepository jobRepository) throws Exception {
    SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
    jobLauncher.setJobRepository(jobRepository);
    jobLauncher.setTaskExecutor(taskExecutor);
    jobLauncher.afterPropertiesSet();
    return jobLauncher;
}

@Bean
public ThreadPoolTaskExecutor msBatchTaskExecutor() {
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    taskExecutor.setCorePoolSize(5);
    taskExecutor.setMaxPoolSize(50);
    taskExecutor.setQueueCapacity(50);
    return taskExecutor;
}

如果您不想使用 @EnableBatchProcessing,那么确实 Java 配置的方法是手动定义基础结构 bean。

请注意,这也是 XML 配置的工作方式,您需要手动定义基础结构 bean,因为 XML 中没有等同于 @EnableBatchProcessing 的东西(有一个开放的 feature request