SoFunction
Updated on 2025-04-29

Detailed explanation of the use of InitializingBean interface and @PostConstruct annotation in Spring

1. Introduction to InitializingBean

1.1 Function introduction

InitializingBean is an interface in the Spring framework that is used to execute custom logic after bean initialization. It provides the afterPropertiesSet() method, which is automatically called by the Spring container at the following times:

  • After the property injection is completed (that is, all properties injected through the setter method or constructor have been set).
  • The last step in the bean initialization phase (after calling the @PostConstruct annotated method, if it exists at the same time).

Core Methods

void afterPropertiesSet(): This method needs to be implemented to define the initialization logic.

1.2 Usage demonstration

step1. Define a Bean that implements InitializingBean

import ;
import ;
 
public class UserBean implements InitializingBean {
 
    private String name;
 
    // Property injection requires setter method    public void setName(String name) {
         = name;
    }
 
    // AfterPropertiesSet method that implements the InitializingBean interface    @Override
    public void afterPropertiesSet() throws Exception {
        ("InitializingBean of afterPropertiesSet() Being called。");
        ("User Name: " + name);
    }
}

step2. Spring configuration class (Java configuration)

import ;
import ;
 
@Configuration
public class AppConfig {
 
    @Bean(name = "userBean")
    public UserBean userBean() {
        UserBean bean = new UserBean();
        ("John Doe"); // Inject properties through setter        return bean;
    }
}

step3. Start Spring container and test

import ;
import ;
 
public class SpringDemo {
    public static void main(String[] args) {
        // Create Spring application context        ApplicationContext context = 
            new AnnotationConfigApplicationContext();
 
        // Get the bean (the initialization logic has been triggered at this time)        UserBean userBean = ("userBean", );
 
        // Example output result:        // InitializingBean's afterPropertiesSet() is called.        // User name: John Doe    }
}

2. Introduction to @PostConstruct

2.1 Function introduction

@PostConstruct is an annotation in Java EE/Jakarta EE (defined in the JSR-250 specification) that marks a method to perform initialization operations after dependency injection is completed. It is commonly used with Spring frameworks and is suitable for scenarios where specific logic is required to be executed when object initialization.

Core functions

1. Initialization method: The annotated method will be called after the following two operations are completed:

  • Dependency injection (DI) completion: Spring container completes the property injection of beans (such as @Autowired, @Value, etc.).
  • Bean Instantiation: After the Bean object is created.

2. Execution time: It is a key step in the life cycle of a bean. It is usually executed after @Autowired or other injection methods are completed, but earlier than the destruction method of @PreDestroy annotation.

Method Constraints

No parameters and no return value: The marked method must be of void type and no parameters.

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

No checked exception is thrown: The method cannot declare that a checked exception is thrown, otherwise a BeanCreationException will be thrown.

@PostConstruct
public void init() throws IOException { ... } // mistake!

Instance method: can only be marked on instance methods and cannot be used for static methods or fields.

Uniqueness: There can only be one @PostConstruct method in a bean, otherwise a conflict will be triggered.

Use scenarios

  • Resource initialization: for example, establishing a database connection, initializing cache, loading configuration, etc.
  • Dependency verification: Check whether the injected dependency is legal.
  • State Initialization: Sets the initial state of the bean.

Things to note

  • Dependency injection must be completed: In the @PostConstruct method, all dependencies injected through @Autowired, etc. are already available.
  • Execution order: Triggered in the following steps: Bean instantiation → Dependency injection → @PostConstruct method → ​​()

2.2 Usage demonstration

import ;
import ;
 
public class MyService {
    @Autowired
    private MyRepository repository;
 
    @PostConstruct
    public void init() {
        // Initialization logic executed after dependency injection is completed        ("Repository is initialized: " + repository);
        // You can perform database connection or other initialization operations here    }
}

3. Comparative analysis of InitializingBean and @PostConstruct

3.1 Comparative Analysis

Contrast dimensions @PostConstruct InitializingBean
source Java EE standard annotation (). Spring framework interface().
Execution timing Execute immediately after property injection is completed (before InitializingBean’s afterPropertiesSet()). Execute after property injection is completed (after @PostConstruct).
How to use Add annotations directly to the method, without implementing the interface. The interface needs to be implemented and the afterPropertiesSet() method is rewrite.
Dependency Dependencies need to be introduced (Java 9+ is built-in, and the lower version needs to be added manually). No additional dependencies required (Spring comes in).
Applicable scenarios Simple initialization logic and hope that the code does not depend on Spring-specific interfaces. Deep integration with Spring lifecycle (such as relying on Spring-specific features) or need to be compatible with old code.
Invasive More concise, no interface intrusion. Interface needs to be implemented, which is invasive.

3.2 Code Demo

Use both at the same time to verify the execution order

step1: Define a Bean that uses both @PostConstruct and InitializingBean

import ;
import ;
 
public class MyBean implements InitializingBean {
 
    public MyBean() {
        ("Constructor is called");
    }
 
    @PostConstruct
    public void initByPostConstruct() {
        ("@PostConstruct method execution");
    }
 
    @Override
    public void afterPropertiesSet() throws Exception {
        ("() implement");
    }
}

step2. Spring configuration class (Java configuration)

import ;
import ;
 
@Configuration
public class AppConfig {
 
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

step3. Start the Spring container and observe the output

import ;
import ;
 
public class Main {
    public static void main(String[] args) {
        ApplicationContext context = 
            new AnnotationConfigApplicationContext();
        
        // Output order:        // 1. The constructor is called        // 2. @PostConstruct method execution        // 3. () Execute    }
}

Output result:

The constructor is called
@PostConstruct method execution
() implement

Key points explanation

1. Execution order:

  • @PostConstruct's method takes precedence over InitializingBean's afterPropertiesSet() execution.
  • This is because when Spring initializes a bean, it first processes the annotation (such as @PostConstruct) and then triggers the interface-defined callback (such as InitializingBean).

2. Constructor and initialization method:

  • The constructor is called when the bean is instantiated (property not injected).
  • Initialization methods (@PostConstruct and InitializingBean) are called after property injection is completed

3.3 Selecting suggestions

Select according to the scene

Recommended scenarios using @PostConstruct:

  • Concise code is required to avoid implementing interfaces.
  • It does not rely on Spring special functions, only basic initialization logic is required.
  • Initialization needs to be performed at an earlier stage (such as initializing the resource immediately after dependency injection).

Recommended scenarios for using InitializingBean:

  • Deep integration with Spring's lifecycle (such as accessing Spring contexts).
  • The project already has a lot of code that uses InitializingBean, without the cost of migration.
  • Initialization logic needs to be executed in stages (such as @PostConstruct first processes the basic logic, and then executes Spring-specific logic through InitializingBean).

Summarize

@PostConstruct is a more modern, concise choice, and is not related to Spring (can be used across frameworks) and is suitable for most scenarios. It can be regarded as an initialization method used in Spring to replace the InitializingBean interface or XML configuration, simplifying code and improving readability.

InitializingBean is suitable for situations where deep coupling to Spring life cycles is required. However, the interface needs to be implemented, which is highly invasive, so @PostConstruct is preferred.

If both are used at the same time, you need to pay attention to the execution order and reasonably plan the logic in stages.

The above is the detailed explanation of the use of the InitializingBean interface and @PostConstruct annotation in Spring. For more information about Spring InitializingBean @PostConstruct, please follow my other related articles!