简体   繁体   English

Spring Batch延迟步骤初始化

[英]Spring Batch delay step initializing

I have a Spring Batch job with two steps. 我有一个包含两个步骤的Spring Batch工作。 The first one downloads a file and the second on processes the file. 第一个下载文件,第二个继续处理文件。 The problem is the second step does not know what the name of the file is until the first step has been run. 问题是第二步直到第一步运行后才知道文件名。

The job automatically already instantaties the steps so it can be run when needed. 作业已自动实例化步骤,因此可以在需要时运行。 I can't think of any way to make sure the step initializes after the first step has been run. 我想不出任何方法来确保在第一步运行后初始化该步骤。

This is the code: 这是代码:

    @Bean
public Job insertIntoDbFromCsvb(){
    return jobs.get("Insert Entity Records Job")
            .incrementer(new RunIdIncrementer())
             .listener(new InsertRecordListener())
            .start(downloadFileStep())
            .next(insertIntoDBStep())
            .build();
}

@Bean
ItemProcessor<Entity, Entity> csvEntityProcessor() {
    return new EntityItemProcessor();
}

@Bean
public Step insertIntoDBStep(){
    return steps.get("Insert Entity Records Step")
            .<Entity, Entity>chunk(500)
            .reader(csvFileReader())
            .processor(csvEntityProcessor())
            .writer(itemWriter())
            .build();
}

@Bean
public Step downloadFileStep(){
    return steps.get("Download File Step")
            .tasklet(new DownloadFileTasklet("https://leidata-preview.gleif.org/storage/golden-copy-files/2018/06/14/49694/20180614-0000-gleif-goldencopy-lei2-golden-copy.csv.zip",
                    fileDao,
                    FileAction.INIT_ENTITY,
                    this))
            .allowStartIfComplete(true)
            .build();
}

@Bean
public FlatFileItemReader<Entity> csvFileReader(){
    System.out.println("file name: " + fileName);
    FlatFileItemReader<Entity> reader = new FlatFileItemReader<>();
    reader.setResource(new ClassPathResource("data/"+this.fileName));
    reader.setStrict(false);
    reader.setLinesToSkip(1);
    reader.setLineMapper(lineMapper());

    return reader;
}

You can see that reader.setResource(new ClassPathResource("data/"+this.fileName)); 您可以看到reader.setResource(new ClassPathResource("data/"+this.fileName)); takes the local variable fileName that I set in the Tasklet of the first step. 接受在第一步的Tasklet中设置的局部变量fileName

Late binding is handled by Spring Batch, you have to set the scope of the bean to step . 后期绑定由Spring Batch处理,您必须将bean的作用域设置为step

Using XML : 使用XML:

<bean id="myReader" scope="step"...>

Using Java (annotation to set on your bean declaration) : 使用Java(在bean声明上设置的注释):

@StepScope

Documentation : https://docs.spring.io/spring-batch/trunk/reference/html/configureStep.html#step-scope 文档: https : //docs.spring.io/spring-batch/trunk/reference/html/configureStep.html#step-scope

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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