Spring属性占位符无法工作

6
我在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"

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

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

有什么想法为什么我会出现错误以及如何解决?


你使用的Spring版本是<3.1还是>=3.1? - Ralph
@Ralph,<spring.version>3.2.2.RELEASE</spring.version> - Alexandr
2个回答

12

导入中的属性占位符只会根据环境变量或系统属性进行解析。

从3.1版本开始,您可以使用ApplicationContextInitializerPropertySources添加到Environment中,以解决您的问题。

请参见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
            }
        }
    } 

我在Spring方面不是很强。我能否在Spring配置文件中声明式地设置ApplicationContextInitializer?我认为仅针对属性文件加载不需要实现它。找不到任何示例。我只能看到Java实现。 - Alexandr
不,你不能以声明的方式完成它。PropertyPlaceHolderConfigurerPropertySourcesPlaceholderConfigurerBeanFactoryPostProcessors,因此导入在解析之前进行。 - Jose Luis Martin
+1:关于链接http://blog.springsource.org/2011/02/15/spring-3-1-m1-unified-property-management/的内容。 - Ralph
@JoseLuisMartin,请告诉我,在Web环境中,当Dispatcher servlet被创建时,如何在基于Java的配置中设置ApplicationContextInitializer。 - Alexandr
对于JavaConfig,请查看@PropertySource注解。 - Jose Luis Martin

2

这个属性文件格式是否有效?我认为你应该使用以下内容来填写app.properties

#possible values: dev test prod
mode=dev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接