【问题标题】:Can I use Spring's util:properties and context:property-placeholder together?我可以一起使用 Spring 的 util:properties 和 context:property-placeholder 吗?
【发布时间】:2018-03-20 15:32:26
【问题描述】:

我在 spring applicationContext.xml 中有以下配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/util 
           http://www.springframework.org/schema/util/spring-util.xsd">

    <context:property-placeholder location="file:///absolute/path/to/foo.properties"/>

    <context:property-placeholder location="file:///absolute/path/to/bar.properties"/>
    <util:properties id="baz" location="file:///absolute/path/to/bar.properties"/>

我可以在加载属性文件的地方放置调试断点,然后查看属性文件的值确实被加载了。

但在我的 bean 中,@Value("#{baz.myProp}") 已解决,而 @Value("${myProp}")PropertyPlaceholderHelper 中爆炸,因为 PropertySourcesPropertyResolver 找不到 myProp

DEBUG [...] - Searching for key 'myProp' in [environmentProperties]
DEBUG [...] - Searching for key 'myProp' in [systemProperties]
DEBUG [...] - Searching for key 'myProp' in [systemEnvironment]
DEBUG [...] - Could not find key 'myProp' in any property source. Returning [null]
DEBUG [...] - Searching for key 'myProp' in [localProperties]
DEBUG [...] - Could not find key 'myProp' in any property source. Returning [null]

为什么会这样以及如何使其工作(使用 $ 属性占位符解析,而不是 # SpEL 语法)?

通过context:property-placeholder 加载的属性是否被util:properties 丢弃/覆盖(只能通过baz 引用访问)?

【问题讨论】:

    标签: spring xml-configuration


    【解决方案1】:

    Turns out 这就是context:property-placeholder 每一行所需要的所有内容,以便让每个人都有机会参与解决该属性:ignore-unresolvable="true"...

    【讨论】:

    • 不要(因为您可能会错过重要的例外情况)。使用单个 property-placeholder 和逗号分隔的位置列表。
    猜你喜欢
    • 2011-11-24
    • 1970-01-01
    • 2012-11-23
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 2014-05-01
    • 2019-02-21
    • 2011-11-30
    相关资源
    最近更新 更多