Calling another job from a processor in spring bat

2020-07-24 04:22发布

问题:

I have a job(=JobA) that reads and processes an input file - this Job is defined using a reader, writer, several processors, listeners and exception handlers and i don't want to change this job definition mainly for backwards compatibility reasons

I want to implement another job(=JobB) that reads files from a directory with a certain criteria and in a certain order and then sends the files to be processed by JobA

I was looking into [MultiResourceItemReader][1]

[1]: http://docs.spring.io/spring-batch/apidocs/org/springframework/batch/item/file/MultiResourceItemReader.html "MultiResourceItemReader" but I don't see how I can incorporate the calling to JobA into this

Is it possible?

回答1:

Consider wrapping the exiting job with a second job and using the batch:job element with job-parameters-extractor within the batch:step element.

The external job should include your logic of required file list with a decider. batch:job will call your exiting job and job-parameters-extractor using the org.springframework.batch.core.step.job.JobParametersExtractor interface that will copy the required file path to the internal job.

Look at the following answer where I used the elements above.

Logically your job will look like

<batch:job id="jobWrapper" incrementer="runIdIncrementer" >
        <batch:step id="createFileList" next="callInternalJob">
            <batch:tasklet ref="fileterRequiredFilesTasklet"/>
        </batch:step>
        <batch:step id="callInternalJob" next="hasMoreFileDecision">
            <batch:job ref="yourJob" job-launcher="jobLauncher"
                job-parameters-extractor="extractCurrentFileParam" />
        </batch:step>
        <batch:decision id="hasMoreFileDecision" decider="hasMoreFileDecider">
            <batch:next on="NEXTFILE" to="callInternalJob" />
            <batch:end  on="COMPLETED" exit-code="COMPLETED" />
        </batch:decision>
    </batch:job>  

fileterRequiredFilesTasklet - create the list of required files and store it in the Job Execution context callInternalJob - Call your exiting job and passing the current file to process via the callInternalJob hasMoreFileDecider - will loop over the list of files created by fileterRequiredFilesTasklet util all were processed.