@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; } ... }
参考:
1.Write to static field from instance method : https://stackoverflow.com/questions/24703755/write-to-static-field-from-instance-method?r=SearchResults
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