【Spring】05 Life cycle initialization callback


In the Spring framework, Lifecycle Callbacks are a powerful mechanism that allows us to perform specific operations at different stages of the Bean life cycle in the Spring container. This gives us a flexible way to manage and control the bean lifecycle.

1. What is a callback?

In Spring, each Bean has a life cycle, which goes through different stages from creation to destruction. Life cycle callbacks are the mechanism for executing specific methods in these stages.

Spring provides two life cycle callback methods: initialization callback and destruction callback.

Insert image description here

Find out if it is a bit like the template method design pattern!

This section will introduce the initialization callback,The next section will introduce the destruction callback.

2. Initialization callback

Spring's initialization callback mechanism provides a way to execute specific logic after dependency injection after bean instantiation. This mechanism brings some benefits, allowing developers to more flexibly manage and customize the Bean initialization process.

Next, we implement the initialization callback in the following two ways:

2.1 Implement the InitializingBean interface

1) Configure Bean

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="springDemo" class="org.example.cheney.SpringDemo">
        <constructor-arg value="SpringDemo"/>
    </bean>
</beans>

2) Create Spring and implement InitializingBean

package org.example.cheney;

import org.springframework.beans.factory.InitializingBean;

public class SpringDemo implements InitializingBean {
    
    
    private String name;

    public SpringDemo(String name) {
    
    
        this.name = name;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
    
    
        System.out.println("Bean " + name + "初始化啦(By InitializingBean)");
    }
}

3) Create startup class

package org.example.cheney;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    
    
    public static void main(String[] args) {
    
    
        String location = "applicationContext.xml";
        ApplicationContext context = new ClassPathXmlApplicationContext(location);
    }
}

Output result:

Insert image description here

2.2 Configure init-method

1) Configure Bean

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="springDemo" class="org.example.cheney.SpringDemo" init-method="initMethod">
        <constructor-arg value="SpringDemo"/>
    </bean>
</beans>

2) Create Spring and create initMethod()

package org.example.cheney;

public class SpringDemo {
    
    
    private String name;

    public SpringDemo(String name) {
    
    
        this.name = name;
    }

    public void initMethod() {
    
    
        System.out.println("Bean " + name + "初始化啦(By init-method)");
    }
}

3) Create startup class

package org.example.cheney;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    
    
    public static void main(String[] args) {
    
    
        String location = "applicationContext.xml";
        ApplicationContext context = new ClassPathXmlApplicationContext(location);
    }
}

Output result:

Insert image description here

Here you can also set the default method at the beans level, as shown below

Insert image description here

3. Execution sequence

In Spring, the execution order of initialization callbacks is: implement the afterPropertiesSet method of the InitializingBean interface -> configure init-method.

Insert image description here

Spring's initialization callback mechanism provides a way to execute specific logic after dependency injection after Bean instantiation. This mechanism brings some benefits, allowing developers to more flexibly manage and customize the Bean initialization process.

4. Advantages and applications

  • Uniform initialization logic: By implementing InitializingBean interface or configurationinit-method, Bean’s initialization logic can be centralized Improve code readability and maintainability in a unified location.
  • Further processing after dependency injection: In the Bean's initialization callback, you can ensure that all dependencies have been injected, and then perform some further processing logic, such as resource Loading, status checking, etc.
  • Framework integration: Some frameworks or libraries may need to be initialized when the application starts. Through Spring's initialization callback, you can easily initialize these frameworks or libraries. Logic integrated into your application.
  • Resource management: Perform resource initialization in the initialization callback, such as opening a database connection, establishing a network connection, etc., to ensure the correct acquisition and configuration of resources.
  • Flexible configuration method: You can choose to use XML configuration, Java configuration or annotation to define the initialization callback, and choose according to personal or team preferences, providing flexibility .
  • Cooperation with other stages of the Spring life cycle: The initialization callback is used in conjunction with other stages of the Spring life cycle (such as the destruction phase of the Bean), making the entire Bean life cycle management more efficient. Complete.
  • Exception thrown in initialization callback: If an exception occurs in the initialization callback, Spring will catch it and convert it to BeanInitializationException, thus blocking Normal startup of the application, improving the security of the initialization process.

Summarize

Lifecycle Callbacks are a powerful feature of the Spring framework, which provide developers with a flexible way to perform specific operations at different stages of a bean's life cycle. Through initialization callbacks, we can better manage and control the components in the application. In actual development, reasonable use of life cycle callbacks can improve the stability and maintainability of applications.

Guess you like

Origin blog.csdn.net/yanyc0411/article/details/135026510
Recommended