向 Spring 环境公开 <property-placeholder> 属性

Posted

技术标签:

【中文标题】向 Spring 环境公开 <property-placeholder> 属性【英文标题】:Expose <property-placeholder> properties to the Spring Environment 【发布时间】: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; 不会将属性暴露给环境。有没有办法强制以这种方式加载的属性可以通过环境访问?

【问题讨论】:

【参考方案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 版本会导致属性以我预期的方式暴露给环境。谢谢!

以上是关于向 Spring 环境公开 <property-placeholder> 属性的主要内容,如果未能解决你的问题,请参考以下文章

升级到 Spring Boot 2 后,如何向 prometheus 公开缓存指标?

SSM环境集成log4j

使用 Docker 向 Laravel 的工匠公开 Elastic Beanstalk 环境变量

Spring Boot 配置优先级顺序

Spring_框架环境搭建

在 WSDL 中介 WSO2 中为 URI 使用变量