"Step" or "Job" Scope for Spring-Batch beans?

membersound picture membersound · Jun 3, 2014 · Viewed 17.6k times · Source

I'm using Spring-Batch v3.0.0 for batch imports. There is a StepScope and a JobScope. How can I know which of them is appropriate?

For example, if I define a custom ItemReader or ItemWriter that should use a specific EntityManager, it could look like this:

@Bean
@Scope("step") //@Scope("job") //custom scope required to inject #jobParameters
public JpaItemWriter<T> jpaItemWriter(EntityManagerFactory emf) {
    JpaItemWriter<T> writer = new JpaItemWriter<T>();
    writer.setEntityManagerFactory(emf);
    return writer;
}

But which scope is right here? And why?

Execution with step scope works, but I feel the itemWriters should maybe be of job scope so that they are not recreated on every step.

I tried switching step to job, but that throws following error: Exception in thread "main" java.lang.IllegalStateException: No Scope registered for scope 'job'

Answer

Eiland picture Eiland · Jul 28, 2014

Since Spring-Batch v3.0.1 you can use @JobScope

Marking a @Bean as @JobScope is equivalent to marking it as @Scope(value="job", proxyMode=TARGET_CLASS)