java - Spring Batch从文件获取数据并传递给过程

标签 java spring spring-batch

对于 Spring 批处理项目,我需要从文件中获取日期,然后需要将此日期传递给过程,然后运行该过程。

然后该过程的结果必须写入 csv 文件。
我尝试使用监听器,但无法做到这一点。

谁能告诉我如何实现这一点,或者如果可能的话,您可以在 github 中分享任何示例代码吗?

最佳答案

首先,您需要从文件中获取日期并将其存储在 JobExecutionContext 中。最简单的解决方案之一是创建一个自定义 Tasklet 来读取文本文件并通过 StepExecutionListener 将结果 String 存储在上下文中

此微线程采用 file 参数并使用键 file.date 存储结果字符串:

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>

然后,您将使用具有后期绑定(bind)的 Chunk 来检索之前存储的值(即使用 #{jobExecutionContext['file.date']})。

读取器将是一个StoredProcedureItemReader:

<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>

编写器将是一个FlatFileItemWriter:

<bean class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
    <property name="resource" value="${file.dest.path}" />
    <property name="lineAggregator" ref="lineAggregator" />
</bean>

关于java - Spring Batch从文件获取数据并传递给过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33568973/

相关文章:

java - 使用 App Engine 自动缩放的 Firebase 身份验证

javascript - 在通过模型传递的 View 上显示列表

java - JdbcBatchItemWriter 多线程

java.lang.UnsatisfiedLinkError : Unable to load library

java - 在 Microsoft Windows Mobile 6.5.3 Professional 上开发 java 应用程序

java - 使用 MethodInvokingFactoryBean 设置非常规 bean

java - 如何使用 quartz 调度程序动态配置 spring 作业

java - Spring批处理中的网格大小

Java:MySQL 对象在关闭连接时抛出错误

java - 如何创建Java类ScheduledThreadPoolExecutor的bean