gpt4 book ai didi

java - Code smell sonarLint - 为静态字段赋值

转载 作者:行者123 更新时间:2023-11-30 06:44:09 26 4
gpt4 key购买 nike

你能改变它以满足 sonarLint 吗?如果我不进行赋值,我的变量的值为 null ...

@SpringBootApplication
public class BwsApplication {
private static ConfigClass config;

public BwsApplication(ConfigClass configClass) {
config = configClass;//SONAR - Remove this assignment of "config"
}

public static void main(String[] args) throws SQLException {
SpringApplication.run(BwsApplication.class, args);
Connection con = config.getConnection();
int number = StudentsManager.getStudentsNumber(con);
QuartzApp qa = new QuartzApp(config);
qa.excecution(number );
}
}

“不应在构造函数中更新静态字段”我需要在静态上下文中使用变量!

最佳答案

该类使用@SpringBootApplication注解。
作为记录,以下是 Spring Boot 在创建 bean 应用程序期间调用的构造函数:

public BwsApplication(ConfigClass configClass) {
config = configClass;//SONAR - Remove this assignment of "config"
}

该类所代表的SpringBootApplication只会被实例化一次,而且只会被实例化一次。所以从逻辑上看,让这个字段成为static字段似乎也不是无效的。但事实上,将其设置为 static 或否并不重要,因为它只会与一个实例共享。将其设为 static 不遗余力。
我认为您将字段设置为 static 是因为您将在 static main 方法中使用它。
但这不是做到这一点的方法。
相反,删除 static 修饰符并将此代码移动到实例 @PostConstruct 方法中,该方法将在对该 bean 执行依赖注入(inject)后执行:

Connection con = config.getConnection();
int number = StudentsManager.getStudentsNumber(con);
QuartzApp qa = new QuartzApp(config);
qa.excecution(number );

这样,您可以引用 config 字段,即使它是一个实例字段。

它可能看起来像:

@SpringBootApplication
public class BwsApplication {

private ConfigClass config;

public BwsApplication(ConfigClass configClass) {
config = configClass;//SONAR - Remove this assignment of "config"
}

public static void main(String[] args) throws SQLException {
SpringApplication.run(BwsApplication.class, args);
}

@PostConstruct
private void postConstruct() {
Connection con = config.getConnection();
int number = StudentsManager.getStudentsNumber(con);
QuartzApp qa = new QuartzApp(config);
qa.excecution(number);
}
}

关于java - Code smell sonarLint - 为静态字段赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51101289/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com