Writing command line interfaces for Spring apps

Posted by chetan on June 29, 2009 in work

I recently needed to script some tasks for a Spring-based app at work so we could shove it into a crontab. It proved to be much easier than I thought.

You can use your spring.xml config file for wiring up your beans as usual, but rather than deal with various property files you can easily override properties on the fly using system properties. See the following example:

In your spring.xml make sure you have this line:

1
2
3
4
5
6
7
8
9
<bean id="propertyConfigurer" 
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <!-- Allow properties to be overriden via 
         system properties -->
    <property name="systemPropertiesMode" value="2" />
    <property name="locations">
        <list> [...snip...] </list>
    </property>
</bean>

Then you can override your aliases either using standard java properties (-Djdbc.url=”mysql://…”) or via your program’s own command line arguments, which is the route I ended up going.

CommandLineParser parser = new GnuParser();
Options options = new Options();
Option brokerOption = new Option("b", "broker", true, "broker uri");
brokerOption.setRequired(true);
options.addOption(brokerOption);
CommandLine line = parser.parse(options, args);
System.setProperty("jms.broker.url", line.getOptionValue("b"));