gpt4 book ai didi

java - 调试 Eclipse 中来自 .properties 文件 null 的 Spring @Value

转载 作者:行者123 更新时间:2023-12-01 04:14:21 25 4
gpt4 key购买 nike

我的代码的目的是从 *.properties 文件加载一些设置值,以便稍后我可以在代码中的某些 if 语句中使用这些值。我想加载一些列表结构,但由于这看起来很难,所以数组就可以了。我还没有真正做到这一点,因为我陷入了从属性文件中加载字符串的小问题。

当我尝试调试使用一些 Spring 特定数据的代码时。我得到了一些有趣的行为,指向断点上方代码中的定义让我知道变量值为 null。

@Value(value = "${ViewableReportFilter.allStates.verify}")
String verifyStringStates;

public ViewableReportFilter() {
viewStates = null;
log.debug("Read in properties for states: verify:" + verifyStringStates);

/*BREAKPOINT HERE*/

在我的 my.properties 文件中:

ViewableReportFilter.allStates.verify=ONHOLD

以及我使用属性文件的配置:

<context:property-placeholder location="classpath:properties/my.properties" order="1" ignore-unresolvable="true" />

最佳答案

Spring 无法在创建对象之前设置该对象的字段。 Spring 做的第一件事是使用反射来实例化您的类。它将根据上下文使用 Class#newInstance() 或使用 Constructor#newInstance()。只有当构造函数完成工作并返回时,Spring 才能再次使用反射来设置字段的值。

另一种方法是将 @Value 带注释的参数放入构造函数参数列表中,并根据 Spring 提供给它的参数在构造函数内设置字段。

public ViewableReportFilter(@Value String verify) {
this.verifyStringStates = verify;
...

浏览Spring documentation for its IoC container.它非常详细地解释了所有这些。

关于java - 调试 Eclipse 中来自 .properties 文件 null 的 Spring @Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19590066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com