首页 > 其他 > 详细

@Autowired静态注入导致的sonar坏味道:Write to static field ...Utils.staticService from instance method ...Utils.init()

时间:2020-04-08 20:52:56      阅读:176      评论:0      收藏:0      [点我收藏+]
sonar扫描出现了一个严重的坏味道Write to static field ...Utils.staticService from instance method ...Utils.init()
 
意思就是:当一个静态变量直接赋值给静态变量,在多线程调用的情况下,容易出现问题。
 
解决方法就是使用两个set方法(一个静态set方法,一个动态set方法),代替动态变量直接赋值给静态变量的写法。
 
修改前的代码:
@Component
public class RuleDocTypeUtils {

     private static final Logger LOGGER =  LoggerFactory.getLogger(RuleDocTypeUtils.class);
     
     private static DocTypeRuleServiceImpl staticService = new  DocTypeRuleServiceImpl();
    
     @Autowired
     private DocTypeRuleServiceImpl dynamicService;
     
     @PostConstruct
     public void init() {
           staticService = dynamicService;
     }

     ...

}

可以看到,在init()方法中动态服务对象直接赋值给静态服务对象,正是这一行出了问题,如果改为使用set注入静态服务对象的方式,一样有这个问题

 

修改后的代码:
@Component
public class RuleDocTypeUtils {

     private static final Logger LOGGER =  LoggerFactory.getLogger(RuleDocTypeUtils.class);
     
     private static DocTypeRuleServiceImpl staticService = new  DocTypeRuleServiceImpl();
    
     @Autowired
     private DocTypeRuleServiceImpl dynamicService;
     
     @PostConstruct
     public void init() {
           setService(dynamicService);
     }

     private void setService(DocTypeRuleServiceImpl  dynamicService) {
           setStaticService(dynamicService);
     }

     private synchronized static void  setStaticService(DocTypeRuleServiceImpl dynamicService) {
           RuleDocTypeUtils.staticService = dynamicService;
     }

     ...

}

 

参考:
    2.FindBugs error: Write to static field from instance method :  https://stackoverflow.com/questions/21136302/findbugs-error-write-to-static-field-from-instance-method#
    3.FindBugs error: Write to static field from instance method :  http://www.hackerav.com/?post=61820

@Autowired静态注入导致的sonar坏味道:Write to static field ...Utils.staticService from instance method ...Utils.init()

原文:https://www.cnblogs.com/xhj123/p/12662388.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!