java – Spring属性占位符无法正常工作

前端之家收集整理的这篇文章主要介绍了java – Spring属性占位符无法正常工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在stackoverflow.com上看过类似的问题,但没有一个解决方案对我有帮助.
我使用的以下配置(maven项目结构):
src / main / resources / properties / app.properties文件
#possible values: dev test prod
mode: dev

在Spring配置中:

<context:property-placeholder location="classpath:properties/app.properties"/>
<import resource="classpath:/spring/db/${mode}-datasource-config.xml"/>

根据${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"

目标/ classes / properties / app.properties文件存在.

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

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

解决方法

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

从版本3.1开始,您可以使用ApplicationContextInitializer将PropertySources添加到Enviroment中,以解决您的问题.

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>

和初始化程序:

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
            }
        }
    }
原文链接:https://www.f2er.com/java/126651.html

猜你在找的Java相关文章