【问题标题】:Spring @Value from .properties file null in debug eclipseSpring @Value from .properties file null 在调试 Eclipse
【发布时间】:2023-03-31 20:40:01
【问题描述】:

我的代码的目的是从 *.properties 文件中加载一些设置值,以便我以后可以在我的代码中的一些 if 语句中使用这些值。我想加载一些列表结构,但是因为这看起来很难,所以一个数组就可以了。我还没有真正做到这一点,因为我被困在从属性文件中加载一个字符串的琐碎事情上。

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

@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" />

【问题讨论】:

  • 该文件中的其他属性是否有效?可能文件没有加载
  • 加载其他属性。
  • 我想看看你对ViewableReportFilter bean 的声明。

标签: java spring debugging


【解决方案1】:

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

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

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

查看Spring documentation for its IoC container.,它详细解释了所有这些。

【讨论】:

  • 这样做会让 Spring 抛出另一个错误。没有默认构造函数!,添加一个空的构造函数会使带有参数的构造函数被跳过
  • @DavidKarlsson 同样,这取决于您期望如何创建 bean。对不起,我假设@Component。如果您使用&lt;bean&gt; 声明,则需要指定constructor-arg
  • @DavidKarlsson 如果在初始化期间您需要对 verifyStringStates 做一些事情,请改用 @PostConstruct 注释方法,以便 Spring 有时间设置您的字段的值,然后调用它.
  • 我没有在 xml 中指定任何新的 ,这是否需要使用我的属性文件中的值(属性文件已被其他类使用)
  • @DavidKarlsson 你有&lt;bean&gt;ViewableReportFilter 吗?如果您希望使用接受参数的构造函数,则不能按原样使用它。
【解决方案2】:

更新了构造函数,并添加了 Autowire 注释。属性文件没有变化,没有 XML。

String arrayOfStrings;

@Autowired
public ViewableReportFilter(
        @Value("${TMSViewableReportFilter.allStates.verify}") String[] verifyStringStates) {
        arrayOfStrings = verifyStringStates;


public logViewableReportFilter() {
    log.debug("Read in properties for states: verify:" + arrayOfString);
}

【讨论】:

  • 我仍然不认为这是在做你认为它在做的事情。您确实没有提供我们帮助您所需的详细信息。
【解决方案3】:

试试这个:

@Value(value = "${allStates.verify}")

在你的财产 my.properties:

allStates.verify=ONHOLD

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    相关资源
    最近更新 更多