Using AsyncItemWriter with CompositeItemWriter

93 views Asked by At

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.

1

There are 1 answers

0
백성욱 On

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 and empCsvWriter) to the CompositeItemWriter first, and delegate this CompositeItemWriter to the AsyncItemWriter.

So, maybe like this,

@Bean
public AsyncItemWriter<Employee> asyncEmployeeWriter() {
    AsyncItemWriter<Employee> asyncItemWriter = new AsyncItemWriter<>();
    asyncItemWriter.setDelegate(compositeItemWriter());
    return asyncItemWriter;
}

@Bean
public CompositeItemWriter<Employee> compositeItemWriter() {
    List<ItemWriter<Employee>> itemWriterList = new ArrayList<>();
    itemWriterList.add(employeeJsonWriter());
    itemWriterList.add(employeeCsvWriter());
    CompositeItemWriter<Employee> compositeItemWriter = new CompositeItemWriter();
    compositeItemWriter.setDelegates(itemWriterList);
    return compositeItemWriter;
}

It works to me. :)