Inject this field value directly into "studentStepOne", the only method that uses it

Viewed 5709

I've developed Spring Boot-Batch code and sonarlint/Sonar-Qube giving me below error. I went through the link, but solution is not understood as per this link: https://rules.sonarsource.com/java/tag/spring/RSPEC-3305.

Inject this field value directly into "studentStepOne", the only method that uses it.

Code:

@Configuration
@PropertySource("classpath:application.properties")
public class StudentJob {
    @Value( "${spring.chunk.size}")
    private String chunkSize;

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private JdbcCursorItemReader<Student> StudentReader;

    @Autowired
    private ItemProcessor<Student, Student> StudentProcessor;

    @Autowired
    private StudentWriter StudentWriter;

    @Bean
    public StudentStepExecuListner StudentStepExecuListner() {
        return new StudentStepExecuListner();
    }

    @Bean("readStudentJob")
    @Primary
    public Job readStudentJob() {
        return jobBuilderFactory.get("readStudentJob")
                .incrementer(new RunIdIncrementer())
                .start(StudentStepOne())
                .build();
    }

    @Bean
    public Step StudentStepOne() {
        return stepBuilderFactory.get("StudentStepOne")
                .<Student, Student>chunk(Integer.parseInt(chunkSize))
                .reader(StudentReader)
                .processor(StudentProcessor)
                .writer(StudentWriter)
                .listener(StudentStepExecuListner())
                .build();
    }
}
2 Answers

Based on the link, it seems self-explanatory:

That means using parameter injection instead of field injection for dependencies that are only used in a single @Bean method.

So for your job, instantiate it like this:

  @Bean("readStudentJob")
  @Primary
  public Job readStudentJob(Step StudentStepOne) {
      return jobBuilderFactory.get("readStudentJob")
              .incrementer(new RunIdIncrementer())
              .start(StudentStepOne)
              .build();
  }

Unrelated, but you should follow java conventions. Methods should use camelcase. StudentStepOne() should be studentStepOne()

Below Answer will help you.

private StepBuilderFactory stepBuilderFactory;

@Autowired
public void setStepBuilderFactory(StepBuilderFactory stepBuilderFactory) {
    this.stepBuilderFactory= stepBuilderFactory;
}

Instead of implementing field Injection, You can go through with setter injection. Field Injection is not recommended.

Related