12、生命周期-@Bean指定初始化和销毁方法

12、生命周期-@Bean指定初始化和销毁方法

  • Bean的生命周期:创建-》初始化-》销毁
  • 容器管理bean的生命周期
  • 我们可以自定义初始方法和销毁方法,容器在bean进行到当期那生命周期的时候调用我们自定的方法
  • 构造(对象创建):
    • 单实例:在容器启动的时候创建
    • 多实例:在实例被每次调用的时候创建对象
  • 初始化:对象创建完成并赋值好,调用初始化方法
  • 销毁:
    • 单实例:在容器关闭的时候进行销毁
    • 多实例:容器不会管理这个bean,不会销毁(可以手动调用)
  1. 指定初始化和销毁方法:
    • 【xml】 指定 init-method="" destroy-method=""
    • 【注解】 @Bean(initMethod = "init",destroyMethod = "destroy")
  2. 通过让Bean实现InitializingBean(定义初始化逻辑)、DisposableBean(定义销毁逻辑)
  3. 可以使用JSR250规范的两个注解:
    • @PostConstruct 在Bean创建完并且属性值赋值完执行
    • @PreDestroy 在Bean销毁之前
  4. BeanPostProcessor:bean的后置处理器,在bean初始化(init)前后进行处理工作
    • postProcessBeforeInitialization 在bean初始化之前
    • postProcessAfterInitialization 在bean初始化之后

12.1 【xml】

<bean id="pension" class="com.hw.springannotation.beans.Pension" scope="prototype" init-method="" destroy-method="">
    <property name="name" value="hw"></property>
    <property name="age" value="18"></property>
</bean>

12.2 【注解】

@Bean(initMethod = "init",destroyMethod = "destroy")
public Car car() {
    return new Car();
}

Car实体类中添加相应的init() 和destroy()方法

package com.hw.springannotation.beans;

/**
 * @Description TODO
 * @Author hw
 * @Date 2018/11/28 16:58
 * @Version 1.0
 */
public class Car {

    public Car() {
        System.out.println("Car construct...");
    }
    public void init(){
        System.out.println("Car init ...");
    }
    public void destroy(){
        System.out.println("Car destroy ...");
    }
}

12.3 测试

package com.hw.springannotation.test;

import com.hw.springannotation.config.MainConfigOfLifeCycle;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @Description TODO
 * @Author hw
 * @Date 2018/11/28 17:01
 * @Version 1.0
 */
public class Test_LifeCycle {
    /**
     * 创建IOC容器
     */
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);

    @Test
    public void test() {
        System.out.println("IOC容器创建完成...");

        // 关闭容器
        applicationContext.close();
    }
}

控制台打印:

多实例的情况下:

原文地址:https://www.cnblogs.com/Grand-Jon/p/10025365.html