Reputation: 125
I need to write a Spring batch custom item writer that uses a footer, but I can't use the delegate pattern. Is there another way to write a Spring batch custom item writer?
Thank you in advance.
Upvotes: 2
Views: 18400
Reputation: 125
I've found the solution. I can't write a custom itemwriter, but I created a bean out and I have overridden the toString method. In this method I have set the output to the file as needed. Then, I created a PassThroughLineAggregator type itemwriter. This itemwriter calls the toString method of the bean output. And that's all!!
Here's the code: MOH_Diaria_Bean_Out.java:
package es.lac.absis.batch.app.percai.domain;
import java.util.ArrayList;
import java.util.List;
public class MOH_Diaria_Bean_Out {
List<MOH_Diaria_Bean> listaBeans = new ArrayList<MOH_Diaria_Bean>();
public List<MOH_Diaria_Bean> getListaBeans() {
return listaBeans;
}
public void setListaBeans(List<MOH_Diaria_Bean> listaBeans) {
this.listaBeans = listaBeans;
}
public void add (MOH_Diaria_Bean bean){
listaBeans.add(bean);
}
@Override
public String toString() {
// TODO Auto-generated method stub
String salida="";
for (int j=0; j<listaBeans.size(); j++) {
MOH_Diaria_Bean bean = listaBeans.get(j);
salida = salida + bean.toString();
if (j<(listaBeans.size()-1)) {
salida = salida + "\n";
}
}
return salida;
}
}
ItemWriter:
<bean id="MOH_FusionadoFicheros_Writer" class="es.lac.absis.batch.arch.internal.writer.AbsisFlatFileItemWriter">
<property name="resource">
<bean class="es.lac.absis.batch.arch.internal.util.AbsisFileSystemResource">
<constructor-arg ref="filePCA00020"></constructor-arg>
</bean>
</property>
<property name="encoding" value="ISO8859_1"></property>
<property name="lineAggregator">
<bean class="org.springframework.batch.item.file.transform.PassThroughLineAggregator">
</bean>
</property>
</bean>
Upvotes: -1
Reputation: 18413
Create a custom ItemWriter
that implements ItemStream
(to manage restartability and footer writing) and overwrite the next methods:
ItemWrite.write(List<> items)
: write items and during writing perform necessary data calculation for footerItemStream.update(ExecutionContext)
: save calculated footer data in write() methodItemStream.open(ExecutionContext)
: restore previously saved footer dataItemStream.close()
: do real footer writing (directly in your own writer or using a callback)Upvotes: 5
Reputation: 2571
Check here
Basically you need to create a class that implements ItemWriter<YourModel>
and FlatFileFooterCallback
In the write
method, enter how data will be written and in the writeFooter
the footer of the file.
Then declare your class as a bean and put it as a writer in your job.
Upvotes: 0