I have a Spring Batch tasklet as follows in my application.
@Service
public class SampleTasklet implements Tasklet {
@Autowired
private UserService userService;
@Override
public RepeatStatus execute(StepContribution contribution,
ChunkContext chunkContext) throws Exception {
System.err.println(userService.getUsers().size());
return RepeatStatus.FINISHED;
}
}
and I have a Service Class as follows.
@Service
@Slf4j
public class UserService {
public Map<String, String> getUsers(){
return null
}
}
Spring Boot class :
@SpringBootApplication
@Slf4j
public class SampleBatchApp {
public static void main(String[] args) {
log.info("Custom DAM Batch Application starting");
SpringApplication.run(SampleBatchApp.class, args);
}
}
Spring Batch File: -- EDITED as per comments.
@Configuration
@EnableBatchProcessing
public class SampleBatch {
@Autowired
public JobBuilderFactory jobBuilderFactory;
@Autowired
public StepBuilderFactory stepBuilderFactory;
@Autowired
public SampleTasklet sampleTasklet;
@Bean
public Job importUserJob() {
return jobBuilderFactory.get("importUserJob")
.start(step1())
.build();
}
@Bean
public Step step1() {
return stepBuilderFactory.get("step1")
.tasklet(sampleTasklet)
.build();
}
}
When I start my application I get an error as follows.
Field userService in SampleTasklet required a bean of type 'UserService' that could not be found.
Can you please explain this weird behavior? I have tried looking for this in multiple places and I think we can't @autowire a service class inside a tasklet. Am I correct?
OK I found the error.
In your SampleBatch
you declare your Bean SampleTasklet
in Java Config. That means you have to make sure all dependencies get injected. That is why you do not get the UserService
autowired.
Make sure that the UserService gets set in
@Bean
public SampleTasklet sampleTasklet(UserService userService){
return new SampleTasklet(userService);
}
and do not forget to add this constructor in your SampleTasklet
and assign the UserService there.
public class SampleTasklet implements Tasklet {
private UserService userService;
public SampleTasklet (UserService userService){
this.userService=userService;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With