一、前言
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变量赋值、然后使用。