Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Initialize Spring bean after construction

farenda 2017-05-06 0

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;

@Service
public class Bean1 {

    @PostConstruct
    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;

@Service
public class Bean2 implements InitializingBean {

    @Autowired
    private Bean1 bean1;

    @Override
    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;

@SpringBootApplication
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.

References:

  • Check out Spring Framework Tutorial for more cool Spring stuff!
Share with the World!
Categories Spring Framework Tags spring-core
Previous: Palindrome detector in Java
Next: Floyd Cycle detection in Java

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored