如何将JobExecutionListener beforeJob方法中的值传递给CustomItemReader

时间:2015-12-04 07:19:05

标签: spring spring-batch

我将在listener的beforeJob方法中编写一个代码,用于将文件从服务器下载到本地系统D://.......之后,已经下载的文件是csv文件,我需要将文件名传递给CustomItemReader,以便我可以在ItemReader中读取此文件。在编写下载文件的代码之前,我需要知道如何将文件名从beforeJob方法传递给ItemReader?有可能吗?

public class AccountStatusChangeListener implements JobExecutionListener {

    final static Logger log = Logger.getLogger(AccountStatusChangeListener.class);

    @Autowired
    AccountStatChangDBUtil accountStatChangDBUtil;

    //Listeners will invoke before execution or after execution of Job

    public void beforeJob(JobExecution jobExecution) {
        log.debug("Invoke before starting of Job");
    }

阅读器

public class AccountStatChangReader implements ItemReader<AccountStatusChangeExtract> {

    final static Logger log = Logger.getLogger(AccountStatChangReader.class);

    FlatFileItemReader<AccountStatusChangeExtract> accountStatusChangeExtractReader=null;

    String fileNameWithTimeStamp;


    public String getFileNameWithTimeStamp() {
        return fileNameWithTimeStamp;
    }

    public void setFileNameWithTimeStamp(String fileNameWithTimeStamp) {
        this.fileNameWithTimeStamp = fileNameWithTimeStamp;
    }

    //Over ride ItemReader read method
    public AccountStatusChangeExtract read() throws Exception,
    UnexpectedInputException, ParseException,
    NonTransientResourceException {
        AccountStatusChangeExtract accountStatusChangeExtract = null;

        log.debug("Inside AccountStatusChangeExtract--(read)");

        try{
            if(null==accountStatusChangeExtractReader ){
                accountStatusChangeExtractReader =new CustomAccountStatChangReader().getAccountStatusChangeItemReader(fileNameWithTimeStamp);
            }
            accountStatusChangeExtract = (AccountStatusChangeExtract) accountStatusChangeExtractReader.read();
            if(null==accountStatusChangeExtract){
                accountStatusChangeExtractReader.close();
            }
        }catch(Exception e){
            log.error("Inside AccountStatusChangeExtract--(read)--Exception--"+e);
        }

        return accountStatusChangeExtract;
    }

1 个答案:

答案 0 :(得分:2)

这是你可以做的,

  1. AccountStatusChangeListener可以将文件名的值存储在JobExecutionContext上的参数中

    jobExecution.getExecutionContext()。put(&#34; filename&#34;,file-name)

  2. 您自定义项目阅读器然后实现beforeStep(StepExecution stepExecution)

    stepExecution.getJobExecution()getExecutionContext()得到(&#34;文件名&#34)。

  3. 这允许您在Job Listener和任何Step Listener之间传递数据