我有一个属性文件,我正在使用 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 ofPropertyPlaceholderConfigurer
. It will still do so if using thespring-context-3.0.xsd
definition of the namespace. That is, you can preserve registration ofPropertyPlaceholderConfigurer
through the namespace, even if using Spring 3.1; simply do not update yourxsi:schemaLocation
and continue using the 3.0 XSD.
因此,我的猜测是您的 XML 未使用正确的 XSD 版本。
关于java - 将 <property-placeholder> 属性暴露给 Spring 环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21277188/