Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Initialize Spring bean after construction

Sometimes there is a need to initialize Spring bean after construction. Basically there are two ways to do that, which we will cover here.

PostConstruct annotation

One way to execute code after Spring Bean has been created is to use standard javax.annotation.PostConstruct annotation. Spring Framework understands it and executes annotated method only after all bean’s dependencies have been injected.

package com.farenda.spring.tutorial.injection.init;

import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

public class Bean1 {

    public void initService() {
        System.out.println("Bean 1 initialized!");

Implement InitializingBean interface

Another way to do post initialization work in Spring is to use its own InitializingBean interface. The interface requires us to implement only one method afterPropertiesSet(), which will be called by Spring after injecting dependencies.

package com.farenda.spring.tutorial.injection.init;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

public class Bean2 implements InitializingBean {

    private Bean1 bean1;

    public void afterPropertiesSet() throws Exception {
        System.out.println("Bean 2 initialized! Bean 1 injected? "
                + (bean1 != null));

Spring Boot app to test

Let’s verify that it actually works and the initialization methods are really called after the beans have been constructed:

package com.farenda.spring.tutorial.injection.init;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

public class App {

    public static void main(String[] args) {
        System.out.println("Main method started.");

        ApplicationContext context = SpringApplication
                .run(App.class, args);

        System.out.println("Context is up!");

        Bean1 service1 = context.getBean(Bean1.class);
        Bean2 service2 = context.getBean(Bean2.class);

        System.out.println("The app is running!");

Now, when we run the app it will print the messages in expected order (Spring Boot logs cut for brevity):

Main method started.
:: Spring Boot ::        (v1.5.2.RELEASE)
... // spring context is getting up
Bean 1 initialized!
Bean 2 initialized! Bean 1 injected? true
INFO 28378 --- [main] Started App in 7.685 seconds (JVM running for 9.388)
Context is up!
The app is running!

We can clearly see that bean initialization works in both ways and the methods have been executed during Spring Context initialization, but before the app is ready to use. This allows us to do some extra setup in our beans, based on their dependencies.


Share with the World!