Spring/Spring boot中静态变量赋值


情形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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM