0

I am writing a spring batch application where my processor returns List, as long as return type is list,

    @Bean(destroyMethod = "")
    @StepScope
public ItemWriterAdapter<List<MyType>> myWriterAdapter()
{
    ItemWriterAdapter<List<MyType>> writer = new ItemWriterAdapter<>();
    writer.setTargetObject(myWriter(null));
    writer.setTargetMethod("write");
    return writer;
}

i keep getting this exception:

org.springframework.batch.item.WriterNotOpenException: Writer must be open before it can be written to at org.springframework.batch.item.file.FlatFileItemWriter.write(FlatFileItemWriter.java:270)

Writer code:

    @Bean
@StepScope
public FlatFileItemWriter< MyType> monetateWriter(@Value(STEP_EC_LOCAL_FILE_PATH) String localFilePath)
{

    
    final FlatFileItemWriter<MyType> writer = new FlatFileItemWriter<>();
    writer.setResource(getLocalFile(localFilePath));
    writer.setHeaderCallback(new MyHeaderCallback());
    writer.setAppendAllowed(true);
    
    writer.setLineAggregator(new DelimitedLineAggregator<MyType>() {
        {
            setDelimiter(COMMA_DELIMITER);
            setFieldExtractor(new BeanWrapperFieldExtractor<MyType>() {
                {
                    setNames(new String[] {"id", "title"});
                }
            });
        }
    });      
    return writer;
}
Baha' Al-Khateib
  • 307
  • 3
  • 10

1 Answers1

0

Your ItemWriterAdapter just calls write on the FlatFileItemWriter. I don't see any added value to using it here. The problem is that this adapter is not correctly scoped as an ItemStream, so the delegate is used without its open method being called properly upfront, hence the error. If you remove this adapter, it should work as expected.

If you are using this adapter for the sake of supporting a List type, I would recommend to clearly define what an item is and use a wrapper type to encapsulate a list of items if needed. This allows you to use the FlatFileItemWriter with an aggregate type without having to use such adapter.

Mahmoud Ben Hassine
  • 17,728
  • 2
  • 12
  • 35
  • Thanks for you reply, Adapter is added as my processor returns a list of items not item, FlatFile write method works on item not list of items, hence adapter is required – Baha' Al-Khateib Mar 11 '21 at 06:36
  • That's incorrect. You have a `FlatFileItemWriter` which is for a single item of type `MyType` and a `ItemWriterAdapter>` which is for a list. Who is going to wrap your items in a `List`? You should not be expecting this to be done automatically by the adapter, that's why I'm saying I see no added value of this adapter. You either need to encapsulate the output type of your processor in an aggregate like `class Items { private List list; }`, or use something like https://stackoverflow.com/questions/24004959/return-multiple-items-from-spring-batch-itemprocessor – Mahmoud Ben Hassine Mar 11 '21 at 08:50