Issue
I've been puzzling over a problem for a few days now and would love to hear your ideas.
I'm working on a Spring Batch application and I need to dynamically select the appropriate ItemWriter. I have 4 ItemWriters and 8 classes, each of which must be processed by one of these ItemWriters. For example:
Class Dog -> FileItemWriter
Class Cat -> DatabaseItemWriter
Class Bird -> AnotherItemWriter
Class Raccoon -> FileItemWriter again
and so on...
At the moment I'm using Classifier and If-else, but it doesn't look good. I would like to get a dynamic version without Hardcode.
Maybe Dependency Injection or reflection can accomplish this?
Update
I tried something like this:
public ItemWriter classify(final Animal animal){
if(animal.getName().eqials("Dog"){
return FileItemWriter();
}else if(animal.getName().eqials("Cat") {
return DatabaseItemWriter();
}
}
Animal is a superclass of all other classes. We got Animal object from Processor.
Solution
You are doing the classification manually in the classify
method which returns a regular item writer. Spring Batch provides the ClassifierCompositeItemWriter for that very use case. You can find an example here.
The example above uses a PatternMatchingClassifier
, but for your use case, the org.springframework.classify.SubclassClassifier
should be the way to go (since you said Animal is a superclass of all other classes
).
Answered By - Fadhel Mahmoud Ben Hassine
Answer Checked By - Gilberto Lyons (JavaFixing Admin)