Java Spring-Batch bean 的“步骤”或“作业”范围?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24017673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Step" or "Job" Scope for Spring-Batch beans?
提问by membersound
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?
我正在使用 Spring-Batch v3.0.0 进行批量导入。有一个StepScope
和一个JobScope
。我怎么知道哪一个是合适的?
For example, if I define a custom ItemReader
or ItemWriter
that should use a specific EntityManager
, it could look like this:
例如,如果我定义了一个自定义ItemReader
或ItemWriter
应该使用一个特定的EntityManager
,它可能如下所示:
@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.
使用step
范围执行是有效的,但我觉得 itemWriters 应该是job
范围的,这样它们就不会在每一步都重新创建。
I tried switching step
to job
, but that throws following error:
Exception in thread "main" java.lang.IllegalStateException: No Scope registered for scope 'job'
我尝试切换step
到job
,但这会引发以下错误:
Exception in thread "main" java.lang.IllegalStateException: No Scope registered for scope 'job'
采纳答案by Eiland
Since Spring-Batch v3.0.1 you can use @JobScope
从 Spring-Batch v3.0.1 开始,您可以使用 @JobScope
Marking a @Bean as @JobScope is equivalent to marking it as @Scope(value="job", proxyMode=TARGET_CLASS)
将@Bean 标记为@JobScope 相当于将其标记为@Scope(value="job", proxyMode=TARGET_CLASS)
回答by membersound
Got it: one has to provide the scope as a bean explicit within the @Configuration
file.
明白了:必须在@Configuration
文件中将作用域作为 bean 显式提供。
@Bean
public JobScope jobScope() {
return new JobScope();
}