Load spring context properties from the command line

I want to write a spring command line program that is initialized with a properties file that is passed as a command line parameter. How can I do that?

Primary class:

public static void main (String [] args) {
    String configFilename = args[0];
    ApplicationContext ctx = new ClassPathXmlApplicationContext(
        "classpath:/context/applicationContext.xml");
    MyBean bean = ctx.getBean(MyBean.class); 
    bean.getStarted();
}

applicationContext.xml:

<context:property-placeholder location="CONFIGFILENAME" ignore-unresolvable="true"/>

How do I get the configuration file name from my main method in the actual spring context so that I can load the correct environment-specific properties?

+5
source share
1 answer

In your case, you can better set the system property for the location of the properties file

System.getProperties().setProperty("location", args[0]);

Then in applicationContext.xml

<context:property-placeholder location="${location}" ignore-unresolvable="true"/>  

Hope this solves your problem.

+6
source

All Articles