(blog-of ‘Alex’)

A personal blog about software development and other things. All opinions expressed here are my own, unless explicitly stated.

Simplest dependency management with Spring

Most of the java developers know about XML and class-based module configurations in Spring.

However, there is another one, arguably even simpler than class-based configuration (everything can be done in your application main function).

This is possible with StaticApplicationContext class that has registerSingleton allowing to imperatively register injectable java bean directly in the code.

This is simple and lightweight, but it is not so obvious what you should do to trigger annotation-driven processing for your beans.

Sample below shows how to do that:

final StaticApplicationContext context = new StaticApplicationContext();

context.registerSingleton("beanPostProcessor", CommonAnnotationBeanPostProcessor.class);
context.registerSingleton("superior", SuperiorImpl.class);
context.registerSingleton("inferior", InferiorImpl.class);

context.refresh(); // Refresh is mandatory before any getBean invocation, otherwise bean processors won't work

final Superior superior = context.getBean(Superior.class);

The most important line is where CommonAnnotationBeanPostProcessor is registered in the DI context.