Spring属性占位符不起作用

Ale*_*ndr 6 java spring tomcat properties maven

我在stackoverflow.com上看过类似的问题,但没有一个解决方案对我有帮助.我使用的以下配置(maven项目结构):src/main/resources/properties/app.properties文件

#possible values: dev test prod
mode: dev
Run Code Online (Sandbox Code Playgroud)

在Spring配置中:

<context:property-placeholder location="classpath:properties/app.properties"/>
<import resource="classpath:/spring/db/${mode}-datasource-config.xml"/>
Run Code Online (Sandbox Code Playgroud)

基于${mode}我想要导入相应数据源配置文件的值.

当我使用mvn clean install tomcat7:run命令运行嵌入式tomcat7时,我收到错误:

10, 2013 5:52:29 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet /SpringWebFlow threw load() exception
java.lang.IllegalArgumentException: Could not resolve placeholder 'mode' in string value "classpath:/spring/db/${mode}-datasource-config.xml"
Run Code Online (Sandbox Code Playgroud)

target/classes/properties/app.properties文件存在.

我正在使用IntelliJ IDEA,在编辑器中我可以单击"$ {mode}" <import resource="classpath:/spring/db/${mode}-datasource-config.xml"/>并在属性文件中查看其值.编辑器本身也改变${mode}为灰色dev显示它可以识别属性值.在编辑器中我看到:<import resource="classpath:/spring/db/dev-datasource-config.xml"/>

任何想法为什么我得到错误以及如何解决?

Jos*_*tin 12

导入中的属性占位符仅针对环境变量或系统属性进行解析.

从版本3.1开始,您可以使用一个ApplicationContextInitializer来添加,PropertySourcesEnviroment解决您的问题.

http://blog.springsource.org/2011/02/15/spring-3-1-m1-unified-property-management/

使用配置文件的其他选项是:http://blog.springsource.org/2011/02/14/spring-3-1-m1-introducing-profile/

编辑

例如:

将初始化程序添加到web.xml

<context-param>
    <param-name>contextInitializerClasses</param-name>
    <param-value>foo.bar.AppContextInitializer</param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)

和初始化程序:

public class AppContextInitializer implements ApplicationContextInitializer<ConfigurableWebApplicationContext> {

        @Override
        public void initialize(ConfigurableWebApplicationContext applicationContext) {
            Properties props;
            try {
                props = PropertiesLoaderUtils.loadAllProperties("/some/path");
                PropertiesPropertySource ps = new PropertiesPropertySource("profile", props);
                applicationContext.getEnvironment().getPropertySources().addFirst(ps);
            } catch (IOException e) {
                // handle error
            }
        }
    } 
Run Code Online (Sandbox Code Playgroud)