Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load properties for spring context from command-line

I want to write a spring command line program that is initialized with a property file which is passed as command line parameter. How can that be done?

Starting 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 config file name over from my main method to the actual spring context so that I can load the correct environment dependent properties?

like image 958
Udo Held Avatar asked Aug 07 '12 09:08

Udo Held


People also ask

How do I pass properties to spring boot?

Spring Boot application converts the command line properties into Spring Boot Environment properties. Command line properties take precedence over the other property sources. By default, Spring Boot uses the 8080 port number to start the Tomcat. Let us learn how change the port number by using command line properties.

How do I add a context path to an application property?

The context path is the name of the URL at which we access the application. The default context path is empty. The context path can be changed in many ways. We can set it in the properties file, with the SERVER_SERVLET_CONTEXT_PATH environment variable, with Java System property, or on the command line.

How does spring load properties file?

properties file in the src/main/resources directory, and then set a Spring profile with the same environment name. For example, if we define a “staging” environment, that means we'll have to define a staging profile and then application-staging. properties.


1 Answers

In your case, you could better set a system property for properties file location

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

Then in applicationContext.xml file

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

Hope this will solve your problem.

like image 92
sundar Avatar answered Oct 23 '22 10:10

sundar