2014-03-12 64 views
0

我想要获取属性的值在Environment上下文中与环境bean配置(如在spring PropertyPlaceholderConfigurer and context:property-placeholder选中的答案)。从弹簧中获取配置的属性

public class SpringsPropertiesProvider implements IPropertiesProvider { 
    @Autowired Environment envinronment; 

    @Override 
    public String getProperty(String key) { 
     return envinronment.getProperty(key); 
    } 

} 

此类注册与下面的XML:

<context:property-placeholder 
    location="classpath:myproject/example.properties" /> 
<context:annotation-config /> 
<bean class="myproject.SpringsPropertiesProvider" id="springsPropertiesProvider"/> 

但SpringsPropertiesProvider.getProperty方法不返回example.properties文件中配置的值。

我在做什么错了,我该如何获得由placeholderconfigurer配置的属性的动态访问?

PS。 在environment.getPropert(key)调用过程中,显示​​org.springframework.core.env.PropertySourcesPropertyResolver在其propertySources字段([systemProperties,systemEnvironment])中只有两个条目,并且这两个条目都不包含任何在example.properties中定义的键。

回答

1

试试这个

<context:property-placeholder 
    location="classpath:myproject/example.properties" ignore-resource-not-found="true"/> 

如果该项目不那么启动,这意味着春天无法找到属性文件。说到这些,你的项目结构是什么样子的?

更新:

以下link解释了为什么这不工作

+0

Geoand谢谢。我几乎按照你的建议检查了这一点 - 通过使文件路径不正确,因此上下文加载失败 - 所以原始路径设置是正确的。 –

+0

如果使用@Value(“$ {nameOfProperty})注入属性,会发生什么? – geoand

+0

刚刚检查 - 正在处理这个。 –