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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With