Spring for Plain old Java Applications (POJAs)
Most J2EE developers have at least heard of the Spring framework and know that it is an excellent framework for creating enterprise applications. I have recently needed to create an application that runs from the command line and is short lived. It has no GUI but I wanted it to be configurable and extendable in various ways. To that end, I defined a bunch of interfaces for the objects in the system to use when interfacing with other objects. Then I started thinking about the implementations of these interfaces and the factory classes I would need to create. I said to myself "Self, doesn't Spring already do this?" and I answered myself, "Why, yes". So I decided to try it.
The result is an extremly configurable application to which I can add or remove functionality with some minor configuration changes. I defined a bean that constituted the root object of the system. Here it is:
package com.dhptech.spring.poja; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * The main class for this application. It is responsible for parsing the * command line and controlling the action. * * @author danap */ public abstract class SpringMain { public static final String NAME = "main"; public static final String CONFIG_XML = "spring.xml"; /** * process the arguments and execute the command. * * @param args the arguments. */ public abstract int process(String[] args); /** * The main function for this application. Sets up the spring context * and dispatces the the main data distributor class. * * @param args the command line arguments. * * @return 0 if no errors occurr. */ public static int main(String[] args) { try { ApplicationContext ctx = new ClassPathXmlApplicationContext(CONFIG_XML); main main = (Main) ctx.getBean(NAME); return main.process(args); } catch( Throwable t ) { t.printStackTrace(); return -1; } } }
Create the spring.xml file with a bean named "main" that extends com.dhptech.spring.poja.Main. Pretty darn simple, huh?
- danapsimer's blog
- 1548 reads


Post new comment