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'
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).
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.
Got it: one has to provide the scope as a bean explicit within the @Configuration
file.
@Bean
public JobScope jobScope() {
return new JobScope();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With