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['input.file.name']}" />
  <property name="lineMapper" ref="lineMapper"/>
</bean>



Java code:

try {
//launcher.run(job, new JobParameters());
JobParametersBuilder jpBuilder = new   JobParametersBuilder().addString("input.file.name", "files/input/test.txt");

 jpBuilder.addString("output.file.name", "files/output/"+System.currentTimeMillis()+"_test.txt");
launcher.run(job, jpBuilder.toJobParameters());
} catch (Exception e) {
e.printStackTrace();
}


Another config used FileSystemResource for resource likes the follow.

<property name="resource">
   <bean class="org.springframework.core.io.FileSystemResource" scope="step" autowire-candidate="false">
     <constructor-arg value="#{jobParameters['input.file.name']}" />
   </bean>
</property>



For ItemWriter, the configuration almost same.
NOTE:
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">
  <list>
    <ref bean="inputFile" />
  </list>
</property>

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

  <property name="filePattern" value="file://%file.name%"/>
</bean>

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


Java Code:

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

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