15

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'

wmaxlees
  • 605
  • 1
  • 5
  • 21
membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • how is `emf` wired? using `@Value`? which is its scope? Also look http://stackoverflow.com/questions/12353570/is-there-a-spring-batch-job-scope?rq=1 – Luca Basso Ricci Jun 03 '14 at 14:26
  • `emf` is also a `@Bean` definition, without specific scope. Regarding your link to that issue: yes, it seems that the job scope was introduced exactly for what I'm trying. But switching from `step` to `job` scope is not working for me... – membersound Jun 03 '14 at 14:30
  • 1
    Why would this not be a singleton? The Job scope really has a very small useful use case. Most other scenarios should be either singleton or step (which is why we took so long to add it in the first place). – Michael Minella Jun 03 '14 at 14:42
  • I need the non-singleton scope to inject `@Value("#{jobParameters[input]}")` (sorry, I should have written that). – membersound Jun 03 '14 at 15:00

2 Answers2

7

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)

Eiland
  • 86
  • 3
3

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

@Bean
public JobScope jobScope() {
    return new JobScope();
}
membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • This doesn't work in my version of spring batch. `JobScope is abstract and cannot be instantiated.` Of course, I don't seem to need it when using the `@JobScope` annotation, so maybe it was just a 3.0.0 thing. – Patrick M Aug 11 '16 at 19:44
  • 1
    I'm using `spring-batch` in context of `spring-boot-1.4.0`nowadays, and not using the `@Bean JobScope` anymore. So, probably this was just a legacy issue. You can now just use both `@StepScope` and `@JobScope` on your `Steps`. I think the problem in the past was the the `JobScope` bean has not been initialized by default. But it is now. – membersound Aug 12 '16 at 07:31