属性公开给 Spring 环境

2024-06-24

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

<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 开始参考 http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html及介绍博客文章 http://spring.io/blog/2011/02/15/spring-3-1-m1-unified-property-management/:

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

所以,我的猜测是你的 XML 是not使用正确的 XSD 版本。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

属性公开给 Spring 环境 的相关文章

随机推荐