I am implementing a custom ItemProcessor<I, O> in spring batch for processing data from a Rest api .
I want access some values from jobParameter inside my ItemProcessor class . Any suggestion on how to do that ?
In Tasklet we can access JobParameter but not sure how to do in ItemProcessor .
MyItemProcessor.java
@Component
public class MyItemProcessor implements ItemProcessor<User, UserDetails> {
@Override
public UserDetails process(User user) throws Exception {
// access values from job parameter here
return null;
}
}
CodePudding user response:
You can make your item processor step-scoped and inject job parameters in it. The following is one way of doing that:
@Component
@StepScope
public class MyItemProcessor implements ItemProcessor<User, UserDetails> {
@Value("#{jobParameters}")
private JobParameters jobParameters;
@Override
public UserDetails process(User user) throws Exception {
// access values from job parameter here
return null;
}
}
You could also inject a specific parameter if you want with something like the following:
@Component
@StepScope
public class MyItemProcessor implements ItemProcessor<User, UserDetails> {
@Value("#{jobParameters['myParameter']}")
private String myParameter;
@Override
public UserDetails process(User user) throws Exception {
// use myParameter as needed here
return null;
}
}
Since field injection is not recommended, you can inject job parameters in your item processor when you define it as a bean, something like:
// Note how nothing related to Spring is used here, and the processor can be unit tested as a regular Java class
public class MyItemProcessor implements ItemProcessor<User, UserDetails> {
private String myParameter;
public MyItemProcessor(String myParameter) {
this.myParameter = myParameter;
}
@Override
public UserDetails process(User user) throws Exception {
// use this.myParameter as needed here
return null;
}
}
Once that in place, you can declare your item processor bean as follows:
@Bean
@StepScope
public MyItemProcessor itemProcessor(@Value("#{jobParameters['myParameter']}") String myParameter) {
return new MyItemProcessor(myParameter);
}
Fore more details about scoped beans, please check the documentation here: Late Binding of Job and Step attributes.