use*_*554 4 java spring spring-batch
上传到spring批处理后传递动态文件名进行处理
我是 Spring Batch 的新手,我想要完成的是从一个应用程序上传一个 csv 文件,然后使用上传文件的文件名向 Spring Batch 发送一个 post 请求,并让 Spring Batch 从它所在的位置获取文件并处理它。
我试图将字符串值传递给阅读器,但我不知道如何在步骤中访问它
// 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();
}
Run Code Online (Sandbox Code Playgroud)
我希望将文件名传递给读者 amd spring batch 可以处理它
您正确地将文件的完整路径作为作业参数传递。但是,您的阅读器需要是步进范围的,以便pathToFile在运行时将作业参数绑定到参数。这称为后期绑定,因为它发生在运行时的后期而不是配置时的早期(当时我们还不知道参数值)。
所以在你的情况下,你的读者可能是这样的:
@Bean
@StepScope
public FlatFileItemReader<Person> reader(@Value("#{jobParameters[fullPathFileName]}") String pathToFile) {
// return reader;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以传递null给reader步骤定义中的方法:
@Bean
public Step step1() {
return stepBuilderFactory.get("step1")
.<Person, Person> chunk(10)
.reader(reader(null))
.processor(processor())
.writer(writer())
.build();
}
Run Code Online (Sandbox Code Playgroud)