Java – spring property placeholders do not work properly

I'm in stackoverflow I've seen similar problems on. Com, but no solution is helpful to me

#possible values: dev test prod
mode: dev

In spring configuration:

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

According to the value of ${mode}, I want to import the corresponding data source configuration file

When I run embedded tomcat7 with the MVN clean install tomcat7: run command, I receive an error:

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 The properties file does not exist

I am using IntelliJ idea. In the editor, I can click < import resource = "classpath" ${mode} ": / spring / db / ${mode} - datasource config. XML" / > and view its value in the properties file The editor itself also changes ${mode} to gray dev, indicating that it can recognize the attribute value In the editor, I see: < import resource = "classpath: / spring / db / dev datasource config. XML" / >

Any idea why I get wrong and how to solve it?

Solution

Attribute placeholders in the import are resolved only for environment variables or system attributes

Starting with version 3.1, you can use applicationcontextinitializer to add propertysources to the environment to solve your problem

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

Another option to do the same is to use a profile: http://blog.springsource.org/2011/02/14/spring-3-1-m1-introducing-profile/

edit

For example:

Add initializer to web xml

<context-param>
    <param-name>contextInitializerClasses</param-name>
    <param-value>foo.bar.AppContextInitializer</param-value>
</context-param>

And initialization procedures:

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
            }
        }
    }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>