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.
Thank you for this tutorial – short and simple ! 🙂
One thing – @Qualifier is not working well with @Autowired for standalone app, got some NPEs during execution time
Why do u have two classess “Launcher” “MainClass.class” ?
Launcher is just an entry point of the application. It contains the “main” method.
MainClass is the main class of your application and, ideally, it should not know anything about Spring.