Monday, April 05, 2010

How to pass filename to FlatFileItemReader with JobParameters in Spring Batch?

 The follow config was tested and succeeded on Spring Batch 2.0.4.
<bean id="flatFileItemReader" class="org.springframework.batch.item.file.FlatFileItemReader" scope="step">
  <property name="resource"  value="file:#{jobParameters['']}" />
  <property name="lineMapper" ref="lineMapper"/>

Java code:

try {
//, new JobParameters());
JobParametersBuilder jpBuilder = new   JobParametersBuilder().addString("", "files/input/test.txt");

 jpBuilder.addString("", "files/output/"+System.currentTimeMillis()+"_test.txt");, jpBuilder.toJobParameters());
} catch (Exception e) {

Another config used FileSystemResource for resource likes the follow.

<property name="resource">
   <bean class="" scope="step" autowire-candidate="false">
     <constructor-arg value="#{jobParameters['']}" />

For ItemWriter, the configuration almost same.
The 'file:' is mandatory if the resource is a file needed to be load from specified path.
The  scope="step" is very important. It seems the file cannot be found if it is missed.
From the reference, I found 'Any bean that uses late-binding must be declared with scope="step".'.

The follow code is is used by SpringBatch 1.x.
Just like the reference metioned, you need to define a listener for step to the proxy to have the access to the StepExecution.

<property name="listeners">
    <ref bean="inputFile" />

<bean id="inputFile" class="org.springframework.batch.core.resource.StepExecutionResourceProxy">

  <property name="filePattern" value="file://"/>

<bean id="myFileItemReader" class="org.springframework.batch.item.file.FlatFil eItemReader">
  <property name="resource" ref="inputFile" />

Java Code:

JobParametersBuilder builder = new JobParametersBuilder();
builder.addString("", "files/input/test.txt");

JobExecution jobExecution = getJobLauncher().run(getJob(), builder.toJobParameters());