欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring ioc 生命周期

程序员文章站 2022-05-24 18:13:09
...
package com.atguigu.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


public class Car implements BeanNameAware,BeanFactoryAware,ApplicationContextAware,BeanPostProcessor,InitializingBean,DisposableBean{
    
    public Car(){
        System.out.println("Car()构造方法");
    }
    
    public void init(){
        System.out.println("car ... init...");
    }
    
    public void detory(){
        System.out.println("car ... detory...");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        
        System.out.println("....ApplicationContextAware....");
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("....BeanFactoryAware....");
        
    }

    @Override
    public void setBeanName(String name) {
        System.out.println("....BeanNameAware...."+name);
        
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("....afterPropertiesSet.类似的如果bean使用了init-method...");
        
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("..前置处理器..postProcessBeforeInitialization..>>.."+beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("..后置处理器..postProcessAfterInitialization...."+beanName);
        return bean;
    }

    @Override
    public void destroy() throws Exception {
        System.out.println(".实现接口销毁方法...DisposableBean>>destroy...");

        
    }

}

 

配置:MainConfigOfLifeCycle

 

package com.atguigu.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.atguigu.bean.Car;
import com.atguigu.bean.Dog2;
import com.atguigu.bean.LifeCycleBean;

/**
 * bean的生命周期:
 *         bean创建---初始化----销毁的过程
 * 容器管理bean的生命周期;
 * 我们可以自定义初始化和销毁方法;容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法
 *
 * 构造(对象创建)
 *         单实例:在容器启动的时候创建对象
 *         多实例:在每次获取的时候创建对象\
 *
 * BeanPostProcessor.postProcessBeforeInitialization
 * 初始化:
 *         对象创建完成,并赋值好,调用初始化方法。。。
 * BeanPostProcessor.postProcessAfterInitialization
 * 销毁:
 *         单实例:容器关闭的时候
 *         多实例:容器不会管理这个bean;容器不会调用销毁方法;
 *
 *
 * 遍历得到容器中所有的BeanPostProcessor;挨个执行beforeInitialization,
 * 一但返回null,跳出for循环,不会执行后面的BeanPostProcessor.postProcessorsBeforeInitialization
 *
 * BeanPostProcessor原理
 * populateBean(beanName, mbd, instanceWrapper);给bean进行属性赋值
 * initializeBean
 * {
 * applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
 * invokeInitMethods(beanName, wrappedBean, mbd);执行自定义初始化
 * applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
 *}
 *
 *
 *
 * 1)、指定初始化和销毁方法;
 *         通过@Bean指定init-method和destroy-method;
 * 2)、通过让Bean实现InitializingBean(定义初始化逻辑),
 *                 DisposableBean(定义销毁逻辑);
 * 3)、可以使用JSR250;
 *         @PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法
 *         @PreDestroy:在容器销毁bean之前通知我们进行清理工作
 * 4)、BeanPostProcessor【interface】:bean的后置处理器;
 *         在bean初始化前后进行一些处理工作;
 *         postProcessBeforeInitialization:在初始化之前工作
 *         postProcessAfterInitialization:在初始化之后工作
 *
 * Spring底层对 BeanPostProcessor 的使用;
 *         bean赋值,注入其他组件,@Autowired,生命周期注解功能,@Async,xxx BeanPostProcessor;
 *
 * @author lfy
 *
 */
//@ComponentScan("com.atguigu.bean")
@Configuration
//@Import({Dog.class,MyBeanPostProcessor.class})
public class MainConfigOfLifeCycle {
    
//    @Scope("prototype")
    @Bean(initMethod="init",destroyMethod="detory")
    public Car car(){
        Car car = new Car();
        beanFactory.addBeanPostProcessor(car);
        return car;
    }
    @Autowired
    private ConfigurableBeanFactory beanFactory;
    
    /*@Bean
    public LifeCycleBean lifeCycleBean(){
        LifeCycleBean lifeCycleBean = new LifeCycleBean();
        beanFactory.addBeanPostProcessor(lifeCycleBean);
        return lifeCycleBean;
    }*/

}

 

测试IOCTest_LifeCycle

package com.atguigu.test;

import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.atguigu.config.MainConfigOfLifeCycle;

public class IOCTest_LifeCycle {
    
    @Test
    public void test01(){
        //1、创建ioc容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
        System.out.println("容器创建完成...");
        applicationContext.getBean("car");
        //关闭容器
        applicationContext.close();
    }

}

结果:

Car()构造方法
....BeanNameAware....car
....BeanFactoryAware....
....ApplicationContextAware....
..前置处理器..postProcessBeforeInitialization..>>..car
....afterPropertiesSet.类似的如果bean使用了init-method...
car ... init...
..后置处理器..postProcessAfterInitialization....car
..前置处理器..postProcessBeforeInitialization..>>..org.springframework.context.event.internalEventListenerProcessor
..后置处理器..postProcessAfterInitialization....org.springframework.context.event.internalEventListenerProcessor
..前置处理器..postProcessBeforeInitialization..>>..org.springframework.context.event.internalEventListenerFactory
..后置处理器..postProcessAfterInitialization....org.springframework.context.event.internalEventListenerFactory
容器创建完成...
二月 27, 2019 11:16:51 上午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.spring[email protected]2a33fae0: startup date [Wed Feb 27 11:16:51 CST 2019]; root of context hierarchy
.实现接口销毁方法...DisposableBean>>destroy...
car ... detory...

 

显示构造方法 > Aware实现 > 前置处理器 > init方法 > 后置处理器> 销毁方法

注意:BeanPostProcessor 需要注册到spring容器中

方法1:另外写一个bean 实现BeanPostProcessor接口

方法2:@Autowired
    private ConfigurableBeanFactory beanFactory;
//    @Scope("prototype")
    @Bean(initMethod="init",destroyMethod="detory")
    public Car car(){
        Car car = new Car();
        beanFactory.addBeanPostProcessor(car);
        return car;
    }