Spring 3 for standalone applications

by Mihhail Lapushkin

Spring is well-known for it’s MVC framework, which is the backbone of today’s J2EE development. Even if you are a web developer every now and then you might have the need to create a command-line tool or even some GUI app. I had this need recently, so I gave Spring 3 a try on the standalone app frontier. To my surprise using it was damn easy!

Here are the steps:

  • Write a bunch of @Component-annotated classes that depend on each other
  • Mark dependencies with @Autowired
  • For external beans:
    • Create a class and mark it with @Configuration
    • Use @Bean-annotated methods to create the objects you need
  • To access  .properties through @Value:
    • Annotate your @Configuration class with @PropertySource(“file-name.properties”)
    • Define the following bean (static is important!):
@Bean
static PropertySourcesPlaceholderConfigurer beanName() {
    return new PropertySourcesPlaceholderConfigurer();
}

And now for the magical main-method-class that puts it all together:

public class Launcher {
    public static void main(String[] args) {
        new AnnotationConfigApplicationContext(Launcher.class.getPackage().getName()).getBean(MainClass.class).init(args);
    }
}

You need to put this class to your root package. It creates the annotation-aware context and passes your root package as the base one for scanning. Once the context is initialized it calls your applications “main method”, which in this example is init. You may also try using @PostConstruct to mark the “main method”, but I am not sure about the consequences. I guess it will work for most cases, where your main class is the root of the dependency tree.

For example of such standalone app project have a look here.