【问题标题】:Property from file is not found with Spring使用 Spring 找不到文件中的属性
【发布时间】:2016-09-29 09:55:17
【问题描述】:

我遇到了无法从我的 Java 代码访问 Spring 属性的问题。

这里是上下文:

<context:property-placeholder ignore-resource-not-found="false"
    location="file:/${setup.properties.directory}/setup.properties"/>

setup.properties 文件如下所示:

paymentProvider.x.url=x

代码是:

SpringContext.INSTANCE.getEnvironment()
                    .getProperty("paymentProvider.x.url");

运行过程中没有错误。但是,上面代码的结果是null

有人知道为什么吗?

【问题讨论】:

标签: java spring properties


【解决方案1】:

修改context:property-placeholder配置如:

<context:property-placeholder location="classpath:setup.properties" />

如果您想在该类级别访问此属性值,请使用如下注释:

@PropertySource(value = { "classpath:setup.properties" })

并读取该类中的属性值 autowire Environment,例如:

@Autowired
private Environment environment;

最后你可以像这样访问:

environment.getRequiredProperty("paymentProvider.x.url");

【讨论】:

    【解决方案2】:

    只有

    @Configuration
    @PropertySource("file:/${setup.properties.directory}/setup.properties")
    public class SpringContext {
    public static final ApplicationContext PROPERTIES_INSTANCE = new AnnotationConfigApplicationContext
            (SpringContext.class);
    }
    

    为我工作。

    【讨论】:

      猜你喜欢
      • 2013-10-22
      • 2019-05-10
      • 2014-07-30
      • 2012-08-27
      • 2013-11-15
      • 2016-09-02
      • 1970-01-01
      • 2012-11-01
      • 1970-01-01
      相关资源
      最近更新 更多