为了账号安全,请及时绑定邮箱和手机立即绑定

将此字段值直接注入“studentStepOne”,这是唯一使用它的方法

将此字段值直接注入“studentStepOne”,这是唯一使用它的方法

RISEBY 2023-01-05 10:12:08
我开发了Spring Boot-Batch代码并sonarlint/Sonar-Qube给出了以下错误。我浏览了链接,但根据此链接无法理解解决方案:https ://rules.sonarsource.com/java/tag/spring/RSPEC-3305 。将此字段值直接注入“studentStepOne”,这是唯一使用它的方法。代码:@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();    }}
查看完整描述

3 回答

?
青春有我

TA贡献1784条经验 获得超8个赞

根据链接,它似乎是不言自明的:

这意味着对仅在单个 @Bean 方法中使用的依赖项使用参数注入而不是字段注入。

所以对于你的工作,像这样实例化它:

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

无关,但你应该遵循 java 约定。方法应该使用驼峰命名法。StudentStepOne()应该studentStepOne()


查看完整回答
反对 回复 2023-01-05
?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

在@Configuration类中,spring 将读取该类,尝试引用所有存在的 bean。因此,如果您只想在方法中引用一个 bean,而不在方法之间共享,则不需要连接到类属性中。只需在您的方法构造函数中接收。


    @Bean

public Step StudentStepOne(StepBuilderFactory stepBuilderFactory) {

    return stepBuilderFactory.get("StudentStepOne")

            .<Student, Student>chunk(Integer.parseInt(chunkSize))

            .reader(StudentReader)

            .processor(StudentProcessor)

            .writer(StudentWriter)

            .listener(StudentStepExecuListner())

            .build();

}

spring 会自动设置 bean。


查看完整回答
反对 回复 2023-01-05
?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

下面的答案将帮助你。


private StepBuilderFactory stepBuilderFactory;


@Autowired

public void setStepBuilderFactory(StepBuilderFactory stepBuilderFactory) {

    this.stepBuilderFactory= stepBuilderFactory;

}

您可以使用 setter 注入,而不是实施字段注入。不推荐现场注入。


查看完整回答
反对 回复 2023-01-05
  • 3 回答
  • 0 关注
  • 102 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信