首页 > 解决方案 > 如何从 Spring Condition 访问文件属性?

问题描述

假设我们有一个简单的 Spring Condition,它必须与属性文件中的文件属性匹配:

public class TestCondition implements Condition {

  @Override
  public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    context.getEnvironment().getProperty("my.property");
    context.getBeanFactory().resolveEmbeddedValue("${my.property}");
    context.getEnvironment().resolvePlaceholders("${my.property}");

    // ... more code
  }
}

不幸的是,上述方法调用都没有返回在属性文件中定义的真实属性。相反,当我为其他两个调用 getProperty 方法和 "${my.property}" 字符串时,我得到 null (显然,该属性尚未解决)。

标签: javaspring

解决方案


怎么样PropertiesLoaderUtils?只需将其放入您的方法中,而不是您所拥有的。

// path to your .properties file
Resource resource = new ClassPathResource("/my.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);

....
String someValue = props.getProperty("someKey", "DEFAULT_VALUE");

如果你的东西不起作用,也许试试这个。


推荐阅读