问题:普通方法调用静态属性时,Sonar会认为有问题
这是我们经常用的,实现Spring的Bean工厂,写一个工具类,
开放一个静态方法:获取实体类
public class BeanHelper implements BeanFactoryAware {
private static BeanFactory factory;
/**
* 获取实体类
*
* @param id
* @return
*/
public static <T> T getBean(String id) {
return (T) factory.getBean(id);
}
/**
* 设置bean工厂
*
* @param beanFactory
*/
@Override
public void setBeanFactory(BeanFactory beanFactory) {
BeanHelper.factory = beanFactory;
}
}
Sonar扫描会报:
Instance methods should not write to "static" fields
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 from synchronized static methods.
This rule raises an issue each time a static field is updated from a non-static method.
翻译:
正确地从非静态方法更新静态字段是很棘手的, 如果在运行中有多个类实例和 / 或多个线程, 则可以很容易地导致 bug。理想情况下, 静态字段只从同步静态方法更新。
每次从非静态方法更新静态字段时, 此规则将引发一个问题。
解决办法:对静态属性包装一个静态方法
public class BeanHelper implements BeanFactoryAware {
private static BeanFactory factory;
/**
* 获取实体类
*
* @param id
* @return
*/
public static <T> T getBean(String id) {
return (T) factory.getBean(id);
}
private static void setFactory(BeanFactory factory) {
BeanHelper.factory = factory;
}
/**
* 设置bean工厂
*
* @param beanFactory
*/
@Override
public void setBeanFactory(BeanFactory beanFactory) {
setFactory(beanFactory);
}
}
包装一个静态 setFactory 方法,Sonar扫描就不会产生问题,由于是静态方法,会被最先初始化,更近一步,可以在 setFactory 方法中,判断 BeanHelper.factory 是否为 null,不为 null 则不赋值,保证不会被多实例或多线程覆盖,此处就不详细写出了。
网友评论