简体   繁体   中英

“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'

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)

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

@Bean
public JobScope jobScope() {
    return new JobScope();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM