关于@Value注解 不能给static静态变量注入值的 问题及解决方案

@Value注解 ,不能给static静态变量注入值。如下,ENV在使用的时候会显示null。

@Value("${environment.variable}")
private static String ENV;

一般解决方案有两种,一种是set方法赋值。另一种是使用@PostConstruct + 中转变量初始化,先用 @Value 给中转变量赋值,然后由中转变量再赋值给static变量。

一:component注解一定要加。

@Component
public class Test {
    public static String ENV;

    @Value("${env}")
    public static void setEnv(String env) {
        Test.ENV= env;
    }
}

二: 两个注解加上

@Component
public class Test {
    public static String ENV;

    @Value("${env}")
    public String temp;

    @PostConstruct
    public void init() {
        ENV= temp;
    }
}
下班记得打卡
原文地址:https://www.cnblogs.com/onlyzhangmeng/p/15016023.html