Can AsyncItemWriter
be used with CompositeItemWriter
?
From the source code:
public class CompositeItemWriter<T> implements ItemStreamWriter<T>, InitializingBean
public interface ItemStreamWriter<T> extends ItemStream, ItemWriter<T>
public class AsyncItemWriter<T> implements ItemStreamWriter<Future<T>>, InitializingBean
The below code snippet to create a CompositeItemWriter using two AsyncItemWriter objects causes a compilation issue at the line - compositeItemWriter.setDelegates(itemWriterList);
with the below error message. What am I missing here?
Required type: List<ItemWriter<? super Employee>>
Provided: List<AsyncItemWriter>
@Bean
public AsyncItemWriter<Employee> asyncEmployeeJsonWriter() {
AsyncItemWriter<Employee> asyncItemJsonWriter = new AsyncItemWriter<>();
asyncItemJsonWriter.setDelegate(empJsonWriter);
return asyncItemJsonWriter;
}
@Bean
public AsyncItemWriter<Employee> asyncEmployeeCsvWriter() {
AsyncItemWriter<Employee> asyncItemCsvWriter = new AsyncItemWriter<>();
asyncItemCsvWriter.setDelegate(empCsvWriter);
return asyncItemCsvWriter;
}
@Bean
public CompositeItemWriter<Employee> compositeItemWriter() {
List<AsyncItemWriter<Employee>> itemWriterList = new ArrayList<>();
itemWriterList.add(asyncEmployeeJsonWriter());
itemWriterList.add(asyncEmployeeCsvWriter());
CompositeItemWriter<Employee> compositeItemWriter = new CompositeItemWriter();
compositeItemWriter.setDelegates(itemWriterList);
return compositeItemWriter;
}
Both empJsonWriter
and empCsvWriter
implement ItemWriter
.
Dependency versions:
- spring-batch-integration-4.3.4.jar
- spring-batch-infrastructure-4.3.4.jar
- spring-boot-starter-batch:jar - 2.4.13
- javax.batch-api:jar - 1.0
P.S.
- There is a related question about AsyncItemWriter with ClassifierCompositeItemWriter - ClassifierCompositeItemWriter with AsyncItemWriter? but I need a code example to use
AsyncItemWriter
withCompositeItemWriter
. - The issue here - Issue in AsyncItemWriter with Spring Batch 5 is about Spring Boot 3 and Spring Batch 5.
I had a similar experience, but I solved it by changing it to the structure below.
Instead of delegating the AsyncItemWriter to the CompositeItemWriter, delegate the ItemWriters(in your code,
empJsonWriter
andempCsvWriter
) to the CompositeItemWriter first, and delegate this CompositeItemWriter to the AsyncItemWriter.So, maybe like this,
It works to me. :)