When I'm writing a Spring command line application which parses command line arguments, how do I pass them to Spring? Would I want to have my main() structured so that it first parses the command line args and then inits Spring? Even so, how would it pass the object holding the parsed args to Spring?
To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. The value of argc should be non negative. argv(ARGument Vector) is array of character pointers listing all the arguments.
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.
Two possibilities I can think of.
1) Set a static reference. (A static variable, although typically frowned upon, is OK in this case, because there can only be 1 command line invocation).
public class MyApp { public static String[] ARGS; public static void main(String[] args) { ARGS = args; // create context } }
You can then reference the command line arguments in Spring via:
<util:constant static-field="MyApp.ARGS"/>
Alternatively (if you are completely opposed to static variables), you can:
2) Programmatically add the args to the application context:
public class MyApp2 { public static void main(String[] args) { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); // Define a bean and register it BeanDefinition beanDefinition = BeanDefinitionBuilder. rootBeanDefinition(Arrays.class, "asList") .addConstructorArgValue(args).getBeanDefinition(); beanFactory.registerBeanDefinition("args", beanDefinition); GenericApplicationContext cmdArgCxt = new GenericApplicationContext(beanFactory); // Must call refresh to initialize context cmdArgCxt.refresh(); // Create application context, passing command line context as parent ApplicationContext mainContext = new ClassPathXmlApplicationContext(CONFIG_LOCATIONS, cmdArgCxt); // See if it's in the context System.out.println("Args: " + mainContext.getBean("args")); } private static String[] CONFIG_LOCATIONS = new String[] { "applicationContext.xml" }; }
Parsing the command line arguments is left as an exercise to the reader.
Have a look at my Spring-CLI library - at http://github.com/sazzer/spring-cli - as one way of doing this. It gives you a main class that automatically loads spring contexts and has the ability to use Commons-CLI for parsing command line arguments automatically and injecting them into your beans.
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