情形1:靜態變量為自動注入的對象
解決方案:設置兩個變量,非靜態變量使用@resource注入Bean,然后使用@PostConstruct在Spring初始化Bean成功后為靜態變量賦值
@Component public class XXUtils { @Resource private XXXProperties xxxPropertiesAutowired; private static XXXProperties xxxProperties; @PostConstruct public void init() { xxxProperties = this.xxxPropertiesAutowired; } }
情形2:靜態變量為普通的基本數據類型,並且從配置文件中讀取初始化值
解決方案:不要在靜態變量上使用@Value注解(spring不允許/不支持把值注入到靜態變量中)
在其對應的set方法是使用@Value注解(set方法不能是靜態的)
/** * 渠道號(XX提供,從配置中讀取並初始化) */ public static String SFT_NOTIFY_CEB_CHANNEL; /** * 機構號(XX’提供,從配置中讀取並初始化) */ public static String INST_CODE; //===================get/Set Method====================== @Value("${mf.cebconfig.SFT_NOTIFY_CEB_CHANNEL}") public void setSFT_NOTIFY_CEB_CHANNEL(String sftNotifyCebChannel) { SFT_NOTIFY_CEB_CHANNEL = sftNotifyCebChannel; logger.info("init SFT_NOTIFY_CEB_CHANNEL value suss,sftNotifyCebChannel={}",sftNotifyCebChannel); } @Value("${mf.cebconfig.INST_CODE}") public void setINST_CODE(String instCode) { INST_CODE = instCode; logger.info("init INST_CODE value suss,instCode={}",instCode); }
參考:
https://www.jianshu.com/p/127310cb90e0
http://blog.csdn.net/zhayuyao/article/details/78553417