10 November, 2009

Command line Spring application configuration

This is basically just a reminder for myself, no I wouldn't have to "invent" it all over again. Most of the time I'm writing web application but occasionally have need for command line app. To keep it simple and clean, here is the application-context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

<context:annotation-config />
<context:component-scan base-package="ee.myapp.commandline" />

<context:property-placeholder location="classpath:application.properties" />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>


And here is the main class to run it all:

public class CLI {
public static void main(String[] args) {
GenericApplicationContext context = new GenericApplicationContext();

ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
// scan for properties file
scanner.scan("conf");

BeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
reader.loadBeanDefinitions("application-context.xml");
context.refresh();
}
}



That way Spring nicely initialize all the bean defined in context and also load property placeholder and does annotation based component scan.

No comments: