java - @PostConstruct执行中@Value静态注解为null

标签 java spring-boot static postconstruct

我面临这个问题:我有一个类,其 @Value 变量声明为静态,如图所示。当我的应用程序启动 @PostConstruct 执行访问此类的方法时,找到具有 null 值的变量。

如果我在 de @PostConstruct 执行后调用此类,我可以看到 @Value 静态变量不为 null 并且具有正确的值。

我怎样才能在 @PostConstruct 执行中拥有这个变量及其实际值?

这是我的代码:

@Component
public class ValidacionesUtils {

public static String variable;

@Value("${access.to.my.variable}")
public void setVariable(String variable) {
    this.variable = variable;
}

@PostConstruct
private void init() {
    if (variable==null) {
        log.error("This is what my application prints");
    } else {
        log.error("This is not printed");
    }
}

}

最佳答案

为什么要声明它是公开的和静态的?

尝试做

@Value("${access.to.my.variable}")
private String variable;

这应该以这种方式在@PostConstruct中可用

关于java - @PostConstruct执行中@Value静态注解为null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56560262/

相关文章:

java - 如何在 Java 中编写一个比较器来概括两种类型的对象?

spring-boot - 是否可以通过配置文件禁用 Spring Boot 的自动配置?

java - SonarQube规则: "Using command line arguments is security-sensitive" in Spring Boot application

c++ - 在初始化函数中初始化静态类成员

c++ - Posix 线程类和启动例程 (pthread)

java - 使用带有自定义序列化的 Gson 序列化枚举映射

java - 使用 16 位像素数据在 Java 中创建图像

java - 从保管库中提取数据库 secret 以执行 Jooq 在本地主机上不起作用

c# - 如何静态声明一个对象数组

java - 声明异常的优点