zoukankan      html  css  js  c++  java
  • bean生命周期

    bean创建-->初始化-->销毁
    容器管理bean的生命周期
    1.构造(对象创建)
      单实例:默认在容器启动的时候创建对象
      多实例:在每次获取对象的时候创建对象
    BeanPostProcessor.postProcessBeforeInitialization(初始化之前工作)
    2.初始化
      对象创建完成,并赋值好,调用初始化方法  
    BeanPostProcessor.postProcessAfterInitialization(初始化之后工作)
    3.销毁:
      单实例:容器关闭的时候
      多实例:容器不会管理这个bean,容器不会调用销毁方法  
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    初始化和销毁三种方式

    1.指定初始化和销毁方法

    代码实现(单实例bean)

    在配置类当中通过@Bean指定init-method和destroy-method

    @ComponentScan("com.ly.springannotation.bean")
    @Configuration
    public class MainConfigOfLifeCycle {
    
        @Bean(initMethod = "init", destroyMethod = "destroy")
        public Car car() {
            return new Car();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    /**
     * @author luoyong
     * @Description: Car
     * @create 2019-12-29 11:39
     * @last modify by [LuoYong 2019-12-29 11:39]
     **/
    @Component
    public class Car {
        public Car() {
            System.out.println("car...constructor...");
        }
    
        public void init() {
            System.out.println("car...init...");
        }
    
        public void destroy() {
            System.out.println("car ... destroy...");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    测试

    public class IOCTest_LifeCycle {
        @Test
        public void test01() {
            //1、创建ioc容器
            AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
            System.out.println("容器创建完成...");
            //关闭容器的时候销毁对象
            applicationContext.close();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    测试结果
    在这里插入图片描述

    多实例的bean

    @ComponentScan(value = "com.ly.springannotation.bean",includeFilters = {@ComponentScan.Filter(type =
            FilterType.ASSIGNABLE_TYPE,classes = {Car.class})},useDefaultFilters = false)
    @Configuration
    public class MainConfigOfLifeCycle {
    
        @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
        @Bean(initMethod = "init", destroyMethod = "destroy")
        public Car car() {
            return new Car();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    测试代码

    public class IOCTest_LifeCycle {
        @Test
        public void test01() {
            //1、创建ioc容器
            AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
            System.out.println("容器创建完成...");
            //多实例bean在获取的时候才会创建对象
            Car car =(Car) applicationContext.getBean("car");
            //关闭容器的时候销毁对象
            applicationContext.close();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    执行结果
    在这里插入图片描述

    多 实 例 b e a n 容 器 不 会 管 理 这 个 b e a n , 不 会 调 用 销 毁 方 法 进 行 销 毁 color{blue}{多实例bean容器不会管理这个bean,不会调用销毁方法进行销毁}beanbean

    2.通过让Bean实现InitializingBean和DisposableBean

    I n i t i a l i z i n g B e a n : 定 义 初 始 化 逻 辑 color{red}{InitializingBean:定义初始化逻辑}InitializingBean
    D i s p o s a b l e B e a n : 定 义 销 毁 逻 辑 color{blue}{DisposableBean:定义销毁逻辑}DisposableBean

    代码实现

    @ComponentScan(value = "com.ly.springannotation.bean",includeFilters = {@ComponentScan.Filter(type =
            FilterType.ASSIGNABLE_TYPE,classes = {Cat.class})},useDefaultFilters = false)
    @Configuration
    public class MainConfigOfLifeCycle {
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    @Component
    public class Cat implements InitializingBean, DisposableBean {
        public Cat() {
            System.out.println("Cat...constructor....");
        }
    
        @Override
        public void destroy() throws Exception {
            System.out.println("Cat...destroy....");
        }
    
        @Override
        public void afterPropertiesSet() throws Exception {
            System.out.println("Cat...afterPropertiesSet....");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    测试

    public class IOCTest_LifeCycle {
        @Test
        public void test01() {
            //1、创建ioc容器
            AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
            System.out.println("容器创建完成...");
            //关闭容器的时候销毁对象
            applicationContext.close();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    测试结果
    在这里插入图片描述

    3.使用JSR250

    @PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法
    @PreDestroy:在容器销毁bean之前通知我们进行清理工作

    代码实现

    @ComponentScan(value = "com.ly.springannotation.bean",includeFilters = {@ComponentScan.Filter(type =
            FilterType.ASSIGNABLE_TYPE,classes = {Dog.class})},useDefaultFilters = false)
    @Configuration
    public class MainConfigOfLifeCycle {
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    @Component
    public class Dog {
    
        public Dog() {
            System.out.println("Dog...constructor...");
        }
    
        //对象创建并赋值之后调用
        @PostConstruct
        public void init() {
            System.out.println("Dog...init...@PostConstruct...");
        }
    
        //容器移除对象之前
        @PreDestroy
        public void destroy() {
            System.out.println("Dog ... destroy...@PreDestroy...");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    测试

    public class IOCTest_LifeCycle {
        @Test
        public void test01() {
            //1、创建ioc容器
            AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
            System.out.println("容器创建完成...");
            //关闭容器的时候销毁对象
            applicationContext.close();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    测试结果
    在这里插入图片描述

    执行初始化方法前后拦截

    BeanPostProcessor

    在bean初始化前后进行一些处理工作
    postProcessBeforeInitialization:在初始化之前工作
    postProcessAfterInitialization:在初始化之后工作

    代码实现

    @ComponentScan(value = "com.ly.springannotation.bean",includeFilters = {@ComponentScan.Filter(type =
            FilterType.ASSIGNABLE_TYPE,classes = {Dog.class, MyBeanPostProcessor.class})},useDefaultFilters = false)
    @Configuration
    public class MainConfigOfLifeCycle {
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    @Component
    public class Dog{
        public Dog() {
            System.out.println("Dog...constructor...");
        }
        //对象创建并赋值之后调用
        @PostConstruct
        public void init() {
            System.out.println("Dog...init...@PostConstruct...");
        }
        //容器移除对象之前
        @PreDestroy
        public void destroy() {
            System.out.println("Dog ... destroy...@PreDestroy...");
        }
    }
    @Component
    public class MyBeanPostProcessor implements BeanPostProcessor {
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            System.out.println("postProcessBeforeInitialization..." + beanName + "=>" + bean);
            return bean;
        }
    
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            System.out.println("postProcessAfterInitialization..." + beanName + "=>" + bean);
            return bean;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    测试

    public class IOCTest_LifeCycle {
        @Test
        public void test01() {
            //1、创建ioc容器
            AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
            System.out.println("容器创建完成...");
            //关闭容器的时候销毁对象
            applicationContext.close();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    测试结果:
    在这里插入图片描述

    源码

    AbstractAutowireCapableBeanFactory 553 populateBean(beanName, mbd, instanceWrapper); 对bean的属性进行赋值
    AbstractAutowireCapableBeanFactory 555 exposedObject = initializeBean(beanName, exposedObject, mbd);

    AbstractAutowireCapableBeanFactory 1604 初始化实现细节

    	protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
    		if (System.getSecurityManager() != null) {
    			AccessController.doPrivileged(new PrivilegedAction<Object>() {
    				@Override
    				public Object run() {
    					invokeAwareMethods(beanName, bean);
    					return null;
    				}
    			}, getAccessControlContext());
    		}
    		else {
    			invokeAwareMethods(beanName, bean);
    		}
    
    		Object wrappedBean = bean;
    		if (mbd == null || !mbd.isSynthetic()) {
    		    //初始化之前执行
    			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    		}
    
    		try {
    		    //执行自定义初始化方法
    			invokeInitMethods(beanName, wrappedBean, mbd);
    		}
    		catch (Throwable ex) {
    			throw new BeanCreationException(
    					(mbd != null ? mbd.getResourceDescription() : null),
    					beanName, "Invocation of init method failed", ex);
    		}
    
    		if (mbd == null || !mbd.isSynthetic()) {
    		    //初始化之后执行
    			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    		}
    		return wrappedBean;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    	@Override
    	public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
    			throws BeansException {
    
    		Object result = existingBean;
    		for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
    			result = beanProcessor.postProcessBeforeInitialization(result, beanName);
    			if (result == null) {
    				return result;
    			}
    		}
    		return result;
    	}
    		@Override
    	public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
    			throws BeansException {
    
    		Object result = existingBean;
    		for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
    			result = beanProcessor.postProcessAfterInitialization(result, beanName);
    			if (result == null) {
    				return result;
    			}
    		}
    		return result;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    拓展

    Spring底层对 BeanPostProcessor 的使用

    bean赋值,注入其他组件,@Autowired,生命周期注解功能,@Async,xxx 都是实现 BeanPostProcessor来完成的
    举例:ApplicationContextAwareProcessor bean当中注入ioc容器

    代码实现

    @Component
    public class Dog implements ApplicationContextAware {
    
        private ApplicationContext applicationContext;
    
    
        public Dog() {
            System.out.println("Dog...constructor...");
        }
    
        //对象创建并赋值之后调用
        @PostConstruct
        public void init() {
            System.out.println("Dog...init...@PostConstruct...");
        }
    
        //容器移除对象之前
        @PreDestroy
        public void destroy() {
            System.out.println("Dog ... destroy...@PreDestroy...");
        }
    
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.applicationContext = applicationContext;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    执行链路图
    ![在这里插入图片描述](https://img-blog.csdnimg.cn/20210102121959354.png?x-oss-process=image/watermark,type_ZmF

    关键步骤:
    AbstractAutowireCapableBeanFactory 1620 wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    AbstractAutowireCapableBeanFactory 409 esult = beanProcessor.postProcessBeforeInitialization(result, beanName);
    ApplicationContextAwareProcessor 97 invokeAwareInterfaces(bean);
    ApplicationContextAwareProcessor 121 
    			if (bean instanceof ApplicationContextAware) {
    				((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
    			}
    Dog 42
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.applicationContext = applicationContext;
        }			
    原文章:https://blog.csdn.net/ly10228/article/details/112062172
  • 相关阅读:
    yzoj P2344 斯卡布罗集市 题解
    yzoj P2350 逃离洞穴 题解
    yzoj P2349 取数 题解
    JXOI 2017 颜色 题解
    NOIP 2009 最优贸易 题解
    CH 4302 Interval GCD 题解
    CH4301 Can you answer on these queries III 题解
    Luogu2533[AHOI2012]信号塔
    Luogu3320[SDOI2015]寻宝游戏
    Luogu3187[HNOI2007]最小矩形覆盖
  • 原文地址:https://www.cnblogs.com/tfil/p/14228408.html
Copyright © 2011-2022 走看看