Method annotated with @Bean is called directly. Use dependency injection instead

Viewed 13189

I'm following a tutorial for Spring Batch and when I write the following code - IntelliJ is complaining that the tasklet(null) call in the job function is called directly:

Method annotated with @Bean is called directly. Use dependency injection instead.

I can get the error to go away if I remove the @Bean annotation from the job - but I want to know what's going on. How can I inject the bean there? Simply writing tasklet(Tasklet tasklet(null)) gives the same error.

@Bean
@StepScope
public Tasklet tasklet(@Value("#{jobParameters['name']}") String name) {
    return ((contribution, chunkContext) -> {
        System.out.println(String.format("This is %s", name));
        return RepeatStatus.FINISHED;
    });
}

@Bean
public Job job() {
    return jobBuilderFactory.get("job")
            .start(stepBuilderFactory.get("step1")
                    .tasklet(tasklet(null))               // tasklet(null) = problem
                    .build())
            .build();
}

asd

1 Answers
@Bean
@StepScope
public Tasklet tasklet(@Value("#{jobParameters['name']}") String name) {
    return ((contribution, chunkContext) -> {
        System.out.println(String.format("This is %s", name));
        return RepeatStatus.FINISHED;
    });
}

@Bean
public Job job(Tasklet tasklet) {
    return jobBuilderFactory.get("job")
            .start(stepBuilderFactory.get("step1")
                    .tasklet(tasklet)
                    .build())
            .build();
}

Spring Bean creation and AOPs are very picky. You need to be very careful with the usage.

In this case you can use bean dependency to solve the TaskLet name being null.

Related