2

I'm using spring-batch to import large datasets to a database. During preparation of the db objects in ItemProcessor, I want to set a field filesHash so that I later know from which file the imported row came from.

Question: how can I optain the current resources filename in ItemProcessor?

I'm using FlatFileItemReader to read the files content line by line. Unfortunately it has a setResource(resource) method, but provides not getter?

The linked question does not answer this!

membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • Possible duplicate of [Get current resource name using MultiResourceItemReader Spting batch](http://stackoverflow.com/questions/22993633/get-current-resource-name-using-multiresourceitemreader-spting-batch) – Luca Basso Ricci Jul 05 '16 at 08:31
  • The linked question has no accepted answer. So what is the answer to my question in your optinion? – membersound Jul 05 '16 at 08:52
  • 3
    Are you using `MultiResourceItemReader`? If so, you can implement the interface `ResourceAware` by one of your domain objects, it will provide the getter to retrieve the current resource. – Tunaki Jul 05 '16 at 09:10
  • How do you inject the resource to your reader? If you do it via job parameter or execution context, couldn't you inject the same value to your processor? – Dean Clark Jul 06 '16 at 17:44
  • yes via jobParameter. But it contains wildcards, thus in the reader I resolve it with `PathMatchingResourcePatternResolver`. I thought I could then somehow get the resource in the processor and get the absolute path from that `Resource`. – membersound Jul 07 '16 at 06:09
  • you can follow this link ? and use ResourceAware. – 3d3n Sep 18 '19 at 10:17

2 Answers2

3

Make your 'item' resource-aware by implementing ResourceAware interface.

public class FileDetailsEntity extends BaseEntity implements ResourceAware {
.... 

@Override
    public void setResource(Resource resource) {
        this.fileName=resource.getFilename();
    }
}
}

You will get the current file name automatically while processing :

public class YourItemProcessor implements ItemProcessor ....{
....
 @Override
    public FileDetailsEntityTemp process(FileDetailsEntity item) {
      // you get the file name by item.getFileName()

...

}
mnhmilu
  • 2,327
  • 1
  • 30
  • 50
1

UPDATE: Definitely just implement ResourceAware on your processor, and let Spring Batch do the work for you.

From the JavaDoc:

Marker interface indicating that an item should have the Spring Resource in which it was read from, set on it. The canonical example is within MultiResourceItemReader, which will set the current resource on any items that implement this interface.

Dean Clark
  • 3,770
  • 1
  • 11
  • 26