Java spring批处理从文件中获取数据并传递到过程
对于Spring批处理项目,我需要从文件中获取日期,然后将该日期传递给过程,然后运行该过程 然后,必须将该过程的结果写入csv文件。Java spring批处理从文件中获取数据并传递到过程,java,spring,spring-batch,Java,Spring,Spring Batch,对于Spring批处理项目,我需要从文件中获取日期,然后将该日期传递给过程,然后运行该过程 然后,必须将该过程的结果写入csv文件。 我尝试使用侦听器,但无法做到这一点 任何人都可以告诉我们如何实现这一点,或者如果可能,您可以在github中共享任何示例代码。首先,您需要从文件中获取日期并将其存储在作业执行上下文中。最简单的解决方案之一是创建一个自定义的Tasklet来读取文本文件,并通过StepExecutionListener将结果String存储在上下文中 此小任务接受一个文件参数,并使用
我尝试使用侦听器,但无法做到这一点
任何人都可以告诉我们如何实现这一点,或者如果可能,您可以在github中共享任何示例代码。首先,您需要从文件中获取日期并将其存储在
作业执行上下文中。最简单的解决方案之一是创建一个自定义的Tasklet
来读取文本文件,并通过StepExecutionListener将结果String
存储在上下文中
此小任务接受一个文件
参数,并使用键文件存储结果字符串。日期
:
public class CustomTasklet implements Tasklet, StepExecutionListener {
private String date;
private String file;
@Override
public void beforeStep(StepExecution stepExecution) {}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
stepExecution.getJobExecution().getExecutionContext().put("file.date", date);
}
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
// Read from file using FileUtils (Apache)
date = FileUtils.readFileToString(file);
}
public void setFile(String file) {
this.file = file;
}
}
这样使用它:
<batch:step>
<batch:tasklet>
<bean class="xx.xx.xx.CustomTasklet">
<property name="file" value="${file.path}"></property>
</bean>
</batch:tasklet>
</batch:step>
写入程序将是一个FlatFileItemWriter
:
<bean class="org.springframework.batch.item.database.StoredProcedureItemReader">
<property name="dataSource" ref="dataSource" />
<property name="procedureName" value="${procedureName}" />
<property name="fetchSize" value="50" />
<property name="parameters">
<list>
<bean class="org.springframework.jdbc.core.SqlParameter">
<constructor-arg index="0" value="#{jobExecutionContext['file.date']}" />
</bean>
</list>
</property>
<property name="rowMapper" ref="rowMapper" />
<property name="preparedStatementSetter" ref="preparedStatementSetter" />
</bean>
<bean class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
<property name="resource" value="${file.dest.path}" />
<property name="lineAggregator" ref="lineAggregator" />
</bean>
这听起来像是一个典型的读取->过程->写入。阅读SpringBatch文档并尝试提出自己的想法,这就是SpringBatch的用途,它的文档写得非常好。