Define an in-memory JobRepository

Viewed 16594

I'm testing Spring Batch using Spring boot. My need is to define jobs working on an Oracle Database but I don't want to save jobs and steps states inside this DB. I've read in the documentation I can use a in-memory repository with the MapJobRepositoryFactoryBean.

Then, I've implemented this bean:

@Bean
    public JobRepository jobRepository() {
        MapJobRepositoryFactoryBean factoryBean = new MapJobRepositoryFactoryBean(new ResourcelessTransactionManager());
        try {
            JobRepository jobRepository = factoryBean.getObject();
            return jobRepository;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

But when my job starts, the first thing Spring Batch does is to create the table in the Oracle DB and continues to use the Oracle datasource. It's like my JobRepository definition isn't taken account.

What did I miss ?

EDIT: I'm using Spring Boot 1.5.3 and Spring Batch 3.0.7

5 Answers

With SpringBoot 2.x, the solution is simpler.

You have to extend the DefaultBatchConfigurer class like this:

@Component
public class NoPersistenceBatchConfigurer extends DefaultBatchConfigurer {
    @Override
    public void setDataSource(DataSource dataSource) {
    }
}

Without datasource, the framework automatically switches to use the MapJobRepository.

If using Spring Boot and @EnableBatchProcessing, you would extend the DefaultBatchConfigurer and override the createJobRepository method. Create a ResourcelessTransactionManager and JobRepository using MapJobRepositoryFactoryBean, the rest of the beans will be auto created by Spring Boot.

@Configuration
public class InMemoryBatchContextConfigurer extends DefaultBatchConfigurer {
    @Bean
    private ResourcelessTransactionManager resoucelessTransactionManager() {
        return new ResourcelessTransactionManager();
    }

    @Override
    protected JobRepository createJobRepository() throws Exception {
        MapJobRepositoryFactoryBean factoryBean = new MapJobRepositoryFactoryBean();
        factoryBean.setTransactionManager(resoucelessTransactionManager());
        return factoryBean.getObject();
    }
}`

Extend DefaultBatchConfigurer class and override createJobRepository method just like below.

@Configuration
public class InMemoryBatchConfigurer extends DefaultBatchConfigurer {
    @Override
    protected JobRepository createJobRepository() throws Exception {
        return new MapJobRepositoryFactoryBean().getObject();
    }
}
Related