Home > OS >  How to use the JdbcTemplate that is configured and available through Spring-Boot in the JobRepositor
How to use the JdbcTemplate that is configured and available through Spring-Boot in the JobRepositor

Time:05-23

Hiho,

we use Spring-Batch 4.3.5 inside a Spring-Boot 2.6.7 service. All things work fine so far. While unit testing the use-cases, we realized that the BatchAutoConfiguration/BatchConfigurerConfiguration creates a JobRepository. This JobRepository needs and wants some JdbcOperations. Because no instance of JdbcOperations is taken from the Spring application context while initializing all the beans, the JobRepositoryFactoryBean decides to create a fresh instance of type JdbcTemplate and attach it to the JobRepository.

Therefore I would like to ask if there is an 'easy' possibility to attach the instance of the JdbcTemplate that is provided by Spring-Boot? Is there another possibility as overwriting the whole initialization mechanism? Do we need to provide our own BatchConfigurer?

Any help is really appreciated! :)

CodePudding user response:

That is not possible. You need to provide a custom BatchConfigurer and use any bean auto-configured by Boot to configure your job repository. Here is a quick example:

@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();
        }
    };
}

In this snippet, the dataSource and jdbcTemplate passed as parameters to the batchConfigurer method will be those auto-configured by Boot (and autowired by Spring).

  • Related