我的程序中有以下代码,在将其与 Maven 集成后,我正在运行 SonarQube 5 以对其进行代码质量检查。
但是,Sonar 要求将封闭方法设为“静态”或删除此集合。方法是setApplicationContext。
如何消除此错误?为什么会出现这个错误?
public class SharedContext implements ApplicationContextAware {
public static final String REPORT_ENGINE_FACTORY = "reportEngineFactory";
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SharedContext.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public Object getBean(String name) {
return applicationContext.getBean(name);
} }
最佳答案
具体来说,您似乎在询问规则 S2696,“实例方法不应写入“静态”字段'
如规则描述详情:
Correctly updating a
static
field from a non-static method is tricky to get right and could easily lead to bugs if there are multiple class instances and/or multiple threads in play. Ideally,static
fields are only updated fromsynchronized static
methods.
因此,问题是告诉您将引发它的方法(大概是 setApplicationContext
)static
,以便在所有类实例中只有一个副本该方法对 static
(即在所有类实例之间共享)字段 applicationContext
进行更新。它还建议使方法同步
,以便一次只有一个实例可以调用该方法。
后期编辑:要查看规则说明,请单击问题消息后显示的“查看规则”或“...”(取决于您的 SonarQube 版本)。
关于java - SONAR 提示 Make the enclosure method "static"or remove this set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39407821/