Reputation: 59
I have a spring batch app that has two separate jobs. They use two different readers, but the processor and the writer are practically the same. The only difference in the writers is that they each should have a property named jobName which holds a different value for each writer. To implement this, I tried using a writer superclass. Is there a way to implement this? How do I call the writers in the config class? What should the class should signature look like for the writers? Since the write() method will be exactly the same for the two writer subclasses, should they be implemented in the superclass or the subclasses?
Job 1
public class JobConfig1{
// ...
@Bean
public Step jobStep(SynchronizedItemStreamReader<InputObj1> someReader1,
ItemWriter someWriter1) {
return stepBuilderFactory
.get("writeAdvantageStep")
.chunk(writeChunkSize)
.reader(someReader1)
.writer(someWriter1) //value of this writer is equal to someWriter1()
.processor(new SomeProcessor())
.faultTolerant()
.build();
}
// reader step ...
// processor step ...
// writer step
// somehow class one of the writer classes (I'll call it SomeWriter1)
}
Job 2
public class JobConfig2{
// ...
@Bean
public Step jobStep(SynchronizedItemStreamReader<InputObj1> someReader2,
ItemWriter someWriter2) {
return stepBuilderFactory
.get("writeAdvantageStep")
.chunk(writeChunkSize)
.reader(someReader2)
.writer(someWriter2) //value of this writer is equal to someWriter2()
.processor(new SomeProcessor())
.faultTolerant()
.build();
}
// reader step ...
// processor step ...
// writer step
// somehow class one of the writer classes (I'll call it SomeWriter2)
}
Writer 1:
public class SomeWriter1 extends SomeWriter {
private String jobName = "NIGHTLY"
}
Writer 2:
public class SomeWriter2 extends SomeWriter {
private String jobName = "INTRADAY"
}
Writer superclass:
//should this class contain the code to write to the destination of the job?
public class SomeWriter implements ItemWriter<DTOObject>{
@Override public void write(List<? extends DTOObject> item) throws Exception {
//do something that involves the jobName property
}
}
Thanks in advance!
Upvotes: 1
Views: 243
Reputation: 97
The below example works . you have any error when you tried.
super writer class
@Slf4j
public abstract class GenericWriter implements ItemWrite<String>{
public abstract String jobName();
@Overrride
public void write(List<? extends String> list) throws Exception{
log.info("job name {}", jobName());
}
}
extending GenericWriter
public class Writer1 extends GenericWriter{
@Override
public String jobName(){
return "Writer 1";
}
}
Upvotes: 1