About
Side Projects
Blog
2021-11-09

Ordering Spring Bean Initialization using SmartLifecycle

Spring Framework is a very popular underlying platform for people working with the Java language. Spring provides plumbing for many needs from Security through to Kafka but at its core it provides a means of “connecting” up the components of the software in a process called “dependency injection” (DI).

These components are call “Beans” and have their own lifecycle. Once a Bean is setup and is “connected” to other beans, it may need to be initialised. One way to achieve this to write an annotated method such as;

@PostConstruct
public void init() {
    // ...
}

This works, but in consideration of the set of all Beans in the software, it is not clear the order in which the Beans will have their @PostConstruct invoked.

One way to achieve some ordering is to implement the org.springframework.context.SmartLifecycle interface. This interface defines methods such as…

That allow the concrete implementing class the ability to be managed by Spring in terms of a lifecycle. To control the order in which Beans are “started”, the class is able to implement the method int getPhase(). The higher the returned int, the later the Bean will be started and the smaller the int, the sooner the Bean will be started.

In this way, it is possible to control the order in which Beans are started.