Spring 引导 - 将应用程序属性注入 Util class 变量

Spring Boot - Injecting application properties into a Util class variable

我想按标题提问

我有一个 util class 如下:

@PropertySource("classpath:application.properties")
public class ServiceUtils {

    @Value("${dummy}")
    public static String SOME_VAR;

    @Value("${dummy}")
    // Baeldung says that it's not possible to inject props to static vars
    public void setSomeVar(String var) {
       SOME_VAR = var;
    }
}

当我启动应用程序并调试时,上面的变量 SOME_VAR 变成 null :(

我知道我在 Util class 中使用它,我认为这是一个反模式。

有人可以帮助我了解我需要更正哪些内容才能使其正常工作吗?

此致

Spring 不允许您在静态变量中注入值。请改用非静态。

如果它必须是静态的,做这样的事情:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ServiceUtils {

    public static String SOME_VAR;

    @Value("${dummy}")
    public void setSomevar(String value) {
        SOME_VAR= value;
    }

}
@Service
@PropertySource("classpath:application.properties")
public class ServiceUtils {

    private static String SOME_VAR;

    @Value("${dummy}")
    public void setSomeVar(String var) {
       this.SOME_VAR = var;
    }
}

尝试像通常在 setter 中那样用 this 赋值。