传递动态文件名以通过发布请求进行处理

时间:2019-05-06 03:19:26

标签: java spring spring-batch

上传到spring批处理后传递动态文件名进行处理

我是spring批处理的新手,我要完成的工作是从一个应用程序上载一个csv文件,然后使用已上传文件的文件名发送一个post请求到spring批处理,并让spring批处理从定位并处理它。

我试图将字符串值传递给读取器,但是我不知道如何在步骤中访问它

// controller where i want to pass the file name to the reader
@RestController

public class ProcessController {

    @Autowired
    JobLauncher jobLauncher;

    @Autowired
    Job importUserJob;

    @PostMapping("/load")
    public BatchStatus Load(@RequestParam("filePath") String filePath) throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {

        JobExecution jobExecution = jobLauncher.run(importUserJob, new JobParametersBuilder()
                .addString("fullPathFileName", filePath)
                .toJobParameters());

        return jobExecution.getStatus();

    }
}

//reader in my configuration class
 @Bean
    public FlatFileItemReader<Person> reader(@Value("#{jobParameters[fullPathFileName]}") String pathToFile) 


// the problem is here at the .reader chain
    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1")
                .<Person, Person> chunk(10)
                .reader(reader(reader))
                .processor(processor())
                .writer(writer())
                .build();
    }

我希望将文件名传递给读取器,并且spring batch可以对其进行处理

1 个答案:

答案 0 :(得分:0)

您正在正确地将完整路径作为作业参数传递给文件。但是,您的阅读器需要具有作业范围(或步骤范围),才能在运行时将作业参数绑定到pathToFile参数。之所以称为late binding,是因为它是在运行时发生的较晚,而不是在配置时发生的(我们当时还不知道参数值)。

因此,在您的情况下,您的读者可能像:

@Bean
@StepScope
public FlatFileItemReader<Person> reader(@Value("#{jobParameters[fullPathFileName]}") String pathToFile) {
   //  return reader;
}

然后,您可以在步骤定义中将null传递给reader方法:

@Bean
public Step step1() {
    return stepBuilderFactory.get("step1")
            .<Person, Person> chunk(10)
            .reader(reader(null))
            .processor(processor())
            .writer(writer())
            .build();
}