将 <property-placeholder> 属性暴露给 Spring Environment

Doc*_*hes 5 java spring properties-file spring-environment

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

<context:property-placeholder location="classpath:foo.properties" />
Run Code Online (Sandbox Code Playgroud)

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

@Value("${prefs.key}")
private String prefValue;
Run Code Online (Sandbox Code Playgroud)

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

@Autowired
private Environment env;

public String getValue(String key) {
  return env.getProperty(key);
}
Run Code Online (Sandbox Code Playgroud)

getValue()这里总是返回null,即使对于属性文件中定义的键也是如此,因为 using<property-placeholder>似乎不会向环境公开属性。有没有办法强制以这种方式加载的属性可以通过环境访问?

nob*_*beh 3

来自 Spring 3.2.x参考和介绍博客文章

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

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