Spring 3.2。*,错误解析具有多个<context:property-placeholder> </context:property-placeholder>的占位符

时间:2014-01-25 00:06:06

标签: spring spring-annotations

Sombody知道这是一个错误还是一个预期的行为

如果您有

的组件
@Value("${foo}")
private String fooValue;

这个配置:

<beans>
    <context:annotation-config />
    <context:component-scan base-package="org.mortar" />
    <aop:aspectj-autoproxy />
    <context:property-placeholder location="classpath:a.properties"/>
    <context:property-placeholder location="classpath:b.properties"/>
</bean>

你得到例外:

java.lang.IllegalArgumentException: Could not resolve placeholder 'foo' in string value "${foo}"

如果您使用单一上下文:property-placeholder,它可以正常工作:

<beans>
    <context:annotation-config />
    <context:component-scan base-package="org.mortar" />
    <aop:aspectj-autoproxy />
    <context:property-placeholder location="classpath:a.properties, classpath:b.properties"/>
</bean>

1 个答案:

答案 0 :(得分:4)

声明

<context:property-placeholder location="classpath:a.properties"/>

注册一个PropertySourcesPlaceholderConfigurer bean和一个名为PlaceholderResolvingStringValueResolver的内部类的bean。这些bean中的每一个都在Spring PropertySource中注册Environment

Spring,当它必须解析String占位符${}值时,会遍历已注册的PlaceholderResolvingStringValueResolver bean。它使用resolveStringValue方法来解析占位符。如果它不能,它会快速失败,即使另一个PlaceholderResolvingStringValueResolver可以解决它。

解决方案是使用单个<context:property-placeholder>,其中所有属性都在一个PropertySourcesPlaceholderConfigurer中注册。

或者,您可以使用属性ignore-unresolvable="true"声明它们。在这种情况下,如果无法解决它,它将不会抛出任何异常。相反,它将尝试下一个。但是,您可能会发现自己有一个未解决的属性,因此我不推荐它。

相关问题