I am trying to access job parameters in an ItemReader
as shown below, but even trying several approaches, I could not find a proper way that is suitable for the lastest Spring Batch version (most of the answers on SO are 8-10 years old).
In order to pass jobParameters to ItemReader, I am using StepExecution
as shown below, but as constructor of CustomDataReader
is executed before the beforeStep
method, I get error on setCollection(collectionName)
line. So, how to fix it?
@Component
public class CustomDataReader extends MongoCursorItemReader<Document> {
private String collectionName;
@BeforeStep
public void beforeStep(final StepExecution stepExecution) {
JobParameters jobParameters = stepExecution.getJobParameters();
collectionName = jobParameters.getParameter("collectionName").getValue().toString();
}
// @Autowired
public CustomDataReader(
@Qualifier("mongoTemplate") MongoTemplate mongoTemplate
) {
setName("customDataReader");
setTargetType(Document.class);
setTemplate(mongoTemplate);
setCollection(collectionName);
setBatchSize(DEFAULT_CHUNK_SIZE);
setLimit(DEFAULT_LIMIT_SIZE);
setQuery(query);
}
}
I also tried to use the following approach with getter-setter, but still the values are null in the constructor of the reader:
@Value("#{jobParameters[collectionName]}")
private String collectionName;
I am looking an elegant solution without using these job parameters in BatchConfig
and only modifying this reader.