【发布时间】:2014-08-14 15:14:04
【问题描述】:
我在加载属性文件中定义的参数时遇到了麻烦,该属性文件使用弹簧上下文 3.2.4.RELEASE。我的web-application-context.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:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<context:property-placeholder system-properties-mode="ENVIRONMENT" ignore-resource-not-found="false" ignore-unresolvable="false" location="file:${runtime.dir}/config/properties.txt" />
<import resource="test-${myBooleanParameter}.xml" />
我的properties.txt 看起来像这样:
myBooleanParameter=true
在我的web.xml 中是以下sn-p:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:web-application-context.xml</param-value>
</context-param>
不幸的是,我收到了这个错误:
Unexpected exception parsing XML document from class path resource [web-application-context.xml]; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'myBooleanParameter' in string value "test-${myBooleanParameter}.xml"
我查看了他正在使用的来源,我认为正确的 propertySource 甚至没有注册PropertySource。这是propertySourcesinPropertyPlaceholderHelper.parseStringValue的列表:
http://i.stack.imgur.com/jkQM2.png
完整的调试日志可以在这里找到:http://tny.cz/0ec9c339
【问题讨论】:
-
import在BeanFactoryPostProcessor之前处理(属性占位符是什么)。在解析import时,只会使用系统或环境属性。不是属性文件,因为它们尚未加载。 -
直到 Spring 3.0 都是如此。从 3.1 开始应该可以:spring.io/blog/2011/02/15/…
-
如果您使用
ApplicationContextInitializer将属性加载为PropertySource并将其注册到Environment,它将起作用。它仍然不适用于属性占位符,因为它是在 import 语句之后加载/处理的,这就是属性占位符方法不起作用的全部原因。 -
没有这样的代码有没有办法做到这一点? gist.github.com/rponte/3989915
-
太糟糕了。但是谢谢你的帮助。然后为我回答了这个问题。
标签: xml spring properties placeholder