一、前言

springboot项目中,有时候需要让static变量使用properties/yml文件中配置的值。

此时,因为是静态变量,所以@Value注解无法直接使用。

虽然也可以在静态方法中直接读取properties/yml文件,然后给静态变量赋值;但是这样写总是比较繁琐,还有可能把properties/yml文件的路径搞错,十分不方便。

下面总结一些简单的方法。

二、实现InitializingBean接口

package com.others.utils;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;


@Configuration
public class StaticPropertiesUtil implements InitializingBean {

    public static Integer staticPort;

    @Value("${port.socket}")
    public Integer port;

    @Override
    public void afterPropertiesSet() throws Exception {
        staticPort = this.port;
    }
}

三、使用@PostConstruct注解

package com.others.utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;


@Configuration
public class StaticPropertiesUtil {

    public static Integer staticPort;

    @Value("${port.socket}")
    public Integer port;

    @PostConstruct
    public void setStaticPort() {
        staticPort = this.port;
    }
}

四、总结

1.上面的方法,都是先用@Value注解读取到配置文件中的值,然后重写afterPropertiesSet方法、或者用@PostConstruct注解,在spring加载到某一步骤时调用这些方法给static变量赋值

2.因此,使用static变量时,不能太早,太早的话会为空;最好等待spring加载完成后、再使用static变量。

3.如果必须在spring加载完成前使用static变量、同时要求static变量读取配置文件中的值、那么可以自己写静态方法直接读取配置文件、给static变量赋值、然后使用。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐