如何在 JobRepository 中使用通过 Spring-Boot 配置并可用的 JdbcTemplate?

How to use the JdbcTemplate that is configured and available through Spring-Boot in the JobRepository?

嗨,

我们在 Spring-Boot 2.6.7 服务中使用 Spring-Batch 4.3.5。到目前为止一切正常。在对用例进行单元测试时,我们意识到 BatchAutoConfiguration/BatchConfigurerConfiguration 创建了一个 JobRepository。这个 JobRepository 需要并且想要一些 JdbcOperations。因为在初始化所有 bean 时没有从 Spring 应用程序上下文中获取 JdbcOperations 的实例,所以 JobRepositoryFactoryBean 决定创建一个 JdbcTemplate 类型的新实例并将其附加到 JobRepository。

所以我想问一下是否有'easy'的可能性来附加Spring-Boot提供的JdbcTemplate实例?是否有另一种可能性覆盖整个初始化机制?我们需要提供自己的 BatchConfigurer 吗?

非常感谢任何帮助! :)

那是不可能的。您需要提供自定义 BatchConfigurer 并使用 Boot 的任何 bean auto-configured 来配置您的作业存储库。这是一个简单的例子:

@Bean
public BatchConfigurer batchConfigurer(DataSource dataSource, JdbcTemplate jdbcTemplate) {
    return new DefaultBatchConfigurer(dataSource) {
        @Override
        protected JobRepository createJobRepository() throws Exception {
            JobRepositoryFactoryBean factoryBean = new JobRepositoryFactoryBean();
            factoryBean.setJdbcOperations(jdbcTemplate);
            // set other properties on the factory bean
            factoryBean.afterPropertiesSet();
            return factoryBean.getObject();
        }
    };
}

在此代码段中,作为参数传递给 batchConfigurer 方法的 dataSourcejdbcTemplate 将是 auto-configured 由 Boot(并由 [=21= 自动装配) ]).