Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'

like image 229
membersound Avatar asked Jun 03 '14 14:06

membersound


People also ask

What is scope step in Spring Batch?

The step scope means that Spring will create the bean only when the step asks for it and that values will be resolved then (this is the lazy instantiation pattern; the bean isn't created during the Spring application context's bootstrapping).

What are the different bean scope in Spring Batch?

Luckily for us, Spring defines two more scopes namely step scope and job scope that help us in defining beans whose lifecycles are tied to the lifecycle of a job and a step respectively.


1 Answers

Got it: one has to provide the scope as a bean explicit within the @Configuration file.

@Bean
public JobScope jobScope() {
    return new JobScope();
}
like image 57
membersound Avatar answered Oct 20 '22 19:10

membersound