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

How to Pass value from JobExecutionListener beforeJob method to CustomItemReader

我将在监听器的 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");
    }

Reader

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. A​​ccountStatusChangeListener 可以将文件名的值存储在 JobExecutionContext 的参数中

    jobExecution.getExecutionContext().put("filename", 文件名)

  2. 您自定义项目 reader 然后执行 beforeStep(StepExecution stepExecution)

    stepExecution.getJobExecution().getExecutionContext().get("filename")

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