zoukankan      html  css  js  c++  java
  • @Autowired静态注入导致的sonar坏味道:Write to static field ...Utils.staticService from instance method ...Utils.init()

    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
  • 相关阅读:
    union
    大端和小端
    迭代器
    STL
    动态内存管理2
    动态内存管理
    关于 FlexBox
    CSS的居中问题
    操作符
    JavaScript介绍
  • 原文地址:https://www.cnblogs.com/xhj123/p/12662388.html
Copyright © 2011-2022 走看看