【问题标题】:Obtaining configured properties from Springs从 Springs 获取配置的属性
【发布时间】:2014-03-12 06:15:49
【问题描述】:

我正在尝试使用 Environment bean 获取在 Springs 上下文中配置的属性值(如 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 中定义的任何键。

【问题讨论】:

    标签: spring


    【解决方案1】:

    试试这个

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

    如果项目没有启动,则意味着 spring 无法找到属性文件。 说到这里,你的项目结构是什么样的?

    更新:

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

    【讨论】:

    • 地理和谢谢。我几乎按照您的建议检查了这一点 - 通过使文件路径不正确并且上下文加载因此失败 - 所以原始路径设置是正确的。
    • 如果你用@Value("${nameOfProperty}) 注入一个属性会发生什么?
    • 环境对象似乎不包含用户指定的属性。看这里:stackoverflow.com/a/21106326/2504224
    • 似乎这个链接中的答案解释了它为什么不起作用。但是我仍然需要找到在不直接传递对 props 的引用的情况下获取配置属性的方法。文件。请参考此链接编辑您的答案。
    猜你喜欢
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多