java - 将 <property-placeholder> 属性暴露给 Spring 环境

标签 java spring properties-file spring-environment

我有一个属性文件,我正在使用 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 ,即使是属性文件中定义的键,因为似乎使用 <property-placeholder>不向环境公开属性。有没有办法强制通过环境访问以这种方式加载的属性?

最佳答案

从 Spring 3.2.x 开始 reference及介绍blog post :

Prior to Spring 3.1, the context:property-placeholder namespace element registered an instance of PropertyPlaceholderConfigurer. It will still do so if using the spring-context-3.0.xsd definition of the namespace. That is, you can preserve registration of PropertyPlaceholderConfigurer through the namespace, even if using Spring 3.1; simply do not update your xsi:schemaLocation and continue using the 3.0 XSD.

因此,我的猜测是您的 XML 使用正确的 XSD 版本。

关于java - 将 <property-placeholder> 属性暴露给 Spring 环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21277188/

相关文章:

java - Java 中反复无常的 Json 解析错误

java - Spring MVC 使用哪个版本的 servlet api?

java - String .replaceAll() 从 Sqlite 数据库获取数据时的意外行为

java - 将属性从 PropertyPlaceholderConfigurer 加载到系统属性

java - IReport - 作为输入流参数的子报表

java.lang.IllegalArgumentException : ResourceLoader must not be null in Spring

java - XSS攻击: change exception thrown in a Spring Boot CRUDRepository ?

java - 与Java 8并行流相比,Spring Batch的任何性能改进均可以处理大量数据

eclipse - 为什么 JSF 属性文件在 Eclipse 中不接受非 ASCII 字符?

hadoop - 是否可以在工作流 oozie 中使用两个 "job.properties"文件?