【问题标题】:@Value static anotation is null in the @PostConstruct execution@Value 静态注解在@PostConstruct 执行中为空
【发布时间】:2019-10-26 20:29:04
【问题描述】:

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

如果我在 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");
    }
}

}

【问题讨论】:

标签: java spring-boot static postconstruct


【解决方案1】:

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

尝试做

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

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

【讨论】:

    猜你喜欢
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 2011-10-17
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    相关资源
    最近更新 更多