【问题标题】:Expose <property-placeholder> properties to the Spring Environment向 Spring 环境公开 <property-placeholder> 属性
【发布时间】:2014-02-12 04:07:47
【问题描述】:

我有一个属性文件,我正在使用 property-placeholder 元素通过 XML 向 Spring 注册:

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

我可以使用@Value 注释访问属性,例如

@Value("${prefs.key}")
private String prefValue;

但我还需要通过 Spring 环境访问属性,例如

@Autowired
private Environment env;

public String getValue(String key) {
  return env.getProperty(key);
}

getValue() 这里总是返回null,即使是在属性文件中定义的键,因为似乎使用&lt;property-placeholder&gt; 不会将属性暴露给环境。有没有办法强制以这种方式加载的属性可以通过环境访问?

【问题讨论】:

    标签: java spring properties-file spring-environment


    【解决方案1】:

    来自 Spring 3.2.x reference 和介绍 blog post

    在 Spring 3.1 之前,context:property-placeholder 命名空间 元素注册了PropertyPlaceholderConfigurer 的实例。它 如果使用 spring-context-3.0.xsd 的定义,仍然会这样做 命名空间。也就是说,您可以保留注册 PropertyPlaceholderConfigurer 通过命名空间,即使使用 春天 3.1;只需不要更新您的xsi:schemaLocation 并继续 使用 3.0 XSD。

    所以,我的猜测是您的 XML 没有使用正确的 XSD 版本。

    【讨论】:

    • 我目前使用spring-context-3.0.xsd 作为 XSD——但奇怪的是,切换到 XSD 的 3.1 版本会导致属性以我预期的方式暴露给环境。谢谢!
    猜你喜欢
    • 2011-02-22
    • 2021-04-06
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 2011-01-25
    • 2016-06-27
    • 2015-01-30
    • 1970-01-01
    相关资源
    最近更新 更多