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
