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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 09:46:00  来源:igfitidea点击:

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

javaspringbatch-processingspring-batch

提问by membersound

I'm using Spring-Batch v3.0.0 for batch imports. There is a StepScopeand 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 ItemReaderor ItemWriterthat should use a specific EntityManager, it could look like this:

例如,如果我定义了一个自定义ItemReaderItemWriter应该使用一个特定的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 stepscope works, but I feel the itemWriters should maybe be of jobscope so that they are not recreated on every step.

使用step范围执行是有效的,但我觉得 itemWriters 应该是job范围的,这样它们就不会在每一步都重新创建。

I tried switching stepto job, but that throws following error: Exception in thread "main" java.lang.IllegalStateException: No Scope registered for scope 'job'

我尝试切换stepjob,但这会引发以下错误: 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 @Configurationfile.

明白了:必须在@Configuration文件中将作用域作为 bean 显式提供。

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