Spring Batch Step Scope如何工作 [英] How Does Spring Batch Step Scope Work

查看:865
本文介绍了Spring Batch Step Scope如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需求,我需要根据其余调用来处理文件,在其中我得到文件名,将其添加到job参数中并在创建bean时使用它.

I have a requirement where I need to process files based on the rest call in which I get the name of the file, I am adding it to the job parameter and using it while creating the beans.

我正在为(读者,作家)创建步骤作用域Bean,并使用job参数.我正在使用异步任务执行器启动作业,因此我在一个新线程中启动该作业,我的问题是如何将这些bean变成当我们定义@StepScope

I am creating step scope Beans for (reader,writer) and using the job parameter.I am starting the job in a new thread as I am using asynchronus task exceutor to launch the job and my question is how will the beans be created by spring when we define @StepScope

jobParametersBuilder.addString("fileName", request.getFileName());
jobExecution = jobLauncher.run(job, jobParametersBuilder.toJobParameters());
@Bean
public JobLauncher jobLauncher() {
    SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
    jobLauncher.setJobRepository(jobRepository());
    jobLauncher.setTaskExecutor(asyncTaskExecutor());
    return jobLauncher;
}

@Bean
@StepScope
public ItemWriter<Object> writer(@Value ("#{jobParameters['fileName']}"String    fileName) {
    JdbcBatchItemWriter<Object> writer = new JdbcBatchItemWriter<>();
    writer.setItemSqlParameterSourceProvider(
        new BeanPropertyItemSqlParameterSourceProvider<Object>());
    writer.setSql(queryCollection.getquery());
    writer.setDataSource(dataSource(fileName));
    return writer;
}

推荐答案

spring batch StepScope对象是特定于步骤而不是单例的对象.您可能知道,Spring中的默认bean范围是单例.但是,通过将spring batch组件指定为StepScope,意味着Spring Batch将使用spring容器为每个步骤执行实例化该组件的新实例.

A spring batch StepScope object is one which is unique to a specific step and not a singleton. As you probably know, the default bean scope in Spring is a singleton. But by specifying a spring batch component being StepScope means that Spring Batch will use the spring container to instantiate a new instance of that component for each step execution.

这对于进行参数后期绑定通常很有用,在参数后期绑定中,可以在StepContextJobExecutionContext级别上指定参数,并且需要用占位符代替,就像您的文件名要求示例一样.

This is often useful for doing parameter late binding where a parameter may be specified either at the StepContext or the JobExecutionContext level and needs to be substituted for a placeholder, much like your example with the filename requirement.

使用StepScope的另一个有用原因是,当您决定并行使用同一组件时.如果组件管理任何内部状态,则重要的是它必须基于StepScope,这样一个线程才不会损害由另一个线程管理的状态(例如,给定步骤的每个线程都有其自己的StepScope组件实例)

Another useful reason to use StepScope is when you decide to reuse the same component in parallel steps. If the component manages any internal state, its important that it be StepScope based so that one thread does not impair the state managed by another thread (e.g, each thread of a given step has its own instance of the StepScope component).

这篇关于Spring Batch Step Scope如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆