Spring Bean生命周期详解「建议收藏」

Spring Bean生命周期详解「建议收藏」SpringBean生命周期详解

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

Spring Bean生命周期详解


1 本文说明

  1. 本文所述基于Spring3.2.7,已由作者通过程序验证,如果和你理解的过程有所不同,首先请查看环境(Spring版本,bean单例,非单例bean级生命周期相关方法会多次执行)是否一样,其后最好自己手动写个测试程序测试一下。另外,本文结合Spring IoC容器初始化过程结合看更容易理解。
  2. 具体环境:
    ApplicationContext context = new ClassPathXmlApplicationContext(path);
    通过BeanFactory创建或者Web环境,即web.xml配置spring容器初始化监听器ContextLoaderListener启动Spring容器,或者其他方式,其中间或有其他外接接口,但这些对bean生命周期并没有什么关系,但需要注意执行流程可能有增加。
  3. BeanFactory和ApplicationContext对于bean后置处理器还有所不同,需要注意,ApplicationContext会自动检测在配置文件中实现了BeanPostProcessor接口的所有bean,并把它们注册为后置处理器,然后在容器创建bean的适当时候调用它,因此部署一个后置处理器同部署其他的bean并没有什么区别。而使用BeanFactory实现的时候,bean 后置处理器必须通过代码显式地去注册。

2 Bean生命周期

概述

  我们知道一个对象的生命周期:创建(实例化-初始化)-使用-销毁,而在Spring中,Bean对象周期当然遵从这一过程,但是Spring提供了许多对外接口,允许开发者对三个过程(实例化、初始化、销毁)的前后做一些操作。
  这里就实例化、初始化区别做一个说明,在Spring Bean中,实例化是为bean对象开辟空间(具体可以理解为构造函数的调用),初始化则是对属性的初始化,说的具体点,这里的属性初始化应该是属性的注入(构造函数也可以有属性的初始化语句,但不属于这一部分),属性注入是通过setter方法注入属性(不管是注解方式还是bean配置property属性方式,其实质都是通过属性的setter方法实现的)。

相关接口、方法说明

  1. Bean自身方法:init-method/destroy-method,通过为配置文件bean定义中添加相应属性指定相应执行方法。
  2. Bean级生命周期接口:BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean这些接口的方法。每个Bean选择实现,可选择各自的个性化操作。
  3. 容器级生命周期接口方法:这个包括了InstantiationAwareBeanPostProcessor 和 BeanPostProcessor 这两个接口实现(前者继承自后者),一般称它们的实现类为“后处理器”(其实我觉得这个名称对新手有误导的意思),这些接口是每个bean实例化或初始化时候都会调用。
  4. 工厂后处理器接口方法:这些方法也是容器级别的,但它们是在上下文装置配置文件之后调用,例如BeanFactoryPostProcessor、 CustomAutowireConfigurer等。
    (这里说一点,这些类名都很长,有的也挺相似,学习的话要仔细看清楚哪个是哪个。)

Bean具体生命周期

  1. postProcessBeanFactory(ConfigurableListableBeanFactory c)
    工厂后处理器(这名字其实只是一个翻译,感觉意义有的时候不一定正确),这个方法其实和Bean生命周期没多少关系,是IoC容器(ApplicationContext)初始化的一部分,详细的可以参考IoC容器初始化一节。具体是容器每一次刷新时(初始化)调用,它是对BeanDefinition进行后处理(BeanDefinition可以参考: Spring IoC容器结构),具体的作用就是可以修改配置文件的各个bean的配置。
    实现:写一个类,实现BeanFactoryPostProcessor接口,重写该方法,并在Spring配置文件中配置该类的一个bean。
  2. postProcessBeforeInstantiation(Class<?>c,String beanName)
    所有bean对象(注1)实例化之前执行,具体点就是执行每个bean类构造函数之前。
    实现:写一个类,实现InstantiationAwareBeanPostProcessor接口,重写该方法,在Spring配置文件中配置该类的一个bean。返回一个Object,但是实际上你返回一个null即可。
  3. bean实例化,调用bean类构造函数
  4. postProcessAfterInstantiation(Object bean,String beanName)
    bean类实例化之后,初始化之前调用
    实现:同第2步,重写该方法,但注意,返回类型这里是boolean,默认是false,你需要更改为true,否则无法注入属性
  5. postProcessPropertyValue(属性名太长,详细查看代码实现)
    属性注入之前调用
    实现:同第2步,重写该方法,注意返回类型是PropertyValue,默认返回null,这里需改为返回第一个参数,详见代码章节3。
  6. setBeanName(String beanName)
    属性注入后调用,该方法作用是让bean类知道自己所在的Bean的name或id属性。
    实现:bean类实现BeanNameAware接口,重写该方法。
  7. setBeanFactory(BeanFactory factory)
    setBeanName后调用,该方法作用是让bean类知道自己所在的BeanFactory的属性(传入bean所在BeanFactory类型参数)。
    实现:bean类实现BeanFactoryAware接口,实现该方法。
  8. postProcessBeforeInitialization(Object bean,String beanName)
    BeanPostProcessor作用是对bean实例化、初始化做些预处理操作(注2)。
    实现:写一个类,实现BeanPostProcessor接口,注意返回类型为Object,默认返回null,需要返回参数中bean。
  9. postProcessBeforeInitialization(Object bean,Strign beanName)
    实现:同第2步,实现该方法,注意点同第8步。(注3)
  10. afterPropertiesSet()
    实现:bean类实现InitializingBean接口,重写该方法。初始化工作,但实现该接口这种方法和Spring耦合,不推荐(这一点DisposableBean一样)。
    11. xml_init()
    实现:spring bean配置文件中配置bean属性init-method=”xml_init”,这个方法名开发者自己定义,与Spring代码解耦。另外需要注意的是,init-method指定的方法不能有参数,有参数抛异常(这一点destroy-method一样)。
  11. postProcessAfterInitialization(Object bean,Strign beanName)
    实现:同第8步,注意点相同。
  12. postProcessAfterInitialization(Object bean,Strign beanName)
    实现:同第2步,注意点同第9步。
  13. 程序执行,bean工作
  14. destroy()
    bean销毁前执行
    实现:bean类实现DisposableBean接口
  15. xml_destroy()
    实现:spring bean配置文件中配置bean属性destroy-method=”xml_destroy”,这个方法名开发者自己定义。

注1:这里的bean类指的是普通bean类,不包括这里实现了各类接口(就是2.2提到的这些接口)而在配置文件中声明的bean。
注2:如果有多个BeanPostProcessor实现类,其执行顺序参考:BeanPostProcessor详解。
注3:InstantiationAwareBeanPostProcessor接口继承自BeanPostProcessor接口,是它的子接口,扩展了两个方法,即bean实例化前后操作,当然前者也会有bean初始化前后操作,当它们两同时存在的话,开发者又同时对两者的postProcessBeforeInitialization、postProcessAfterInitialization方法实现了,先回去执行BeanPostProcessor的方法,再去执行InstantiationAwareBeanPostProcessor的。

3 代码实现

1.bean类

package com.fcc.spring.test;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;

import java.io.Serializable;

/** * Created by fuchaochao on 16/8/5. */
public class HelloWorld implements BeanNameAware,BeanFactoryAware,InitializingBean,DisposableBean{ 
   
    private String message;

    public HelloWorld(){
        System.out.println("3.HelloWorld struct.......");
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void xml_init(){
        //xml开头的表示配置文件配置,这里是bean配置中init-method配置调用
        System.out.println("11.HelloWorld 初始化(init-method)");
    }
    public void xml_destroy(){
        //destroy-method 配置调用
        System.out.println("16.HelloWorld 销毁(destroy-method)");
    }

    public void setBeanName(String s) {
        //属性注入后调用
        System.out.println("6.setBeanName(BeanNameAware) 属性注入后调用, 此时s = " + s);
    }

    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        //setBeanName 后调用
        System.out.println("7.setBeanFactory(BeanFactory) setBeanName后调用");
    }

    public void afterPropertiesSet() throws Exception {
        //processBeforeInitialization(BeanPostProcessor)后调用
        System.out.println("10.afterPropertiesSet(InitializingBean) processBeforeInitialization之后,配置的xml_init之前调用");
    }

    public void destroy() throws Exception {
        System.out.println("15.destroy(DisposableBean) 在processAfterInitialization之后,配置的xml_destroy之前调用");
    }
}

2.BeanFactoryPostProcessor类

package com.fcc.spring.test;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

/** * Created by fuchaochao on 16/8/12. */
public class BeanFactoryPostProcessorTest implements BeanFactoryPostProcessor { 
   
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        //configurableListableBeanFactory.getBeanDefinition("appcontext-service.xml");
        System.out.println("1.postProcessBeanFactory(BeanFactoryPostProcessor) 工厂后处理器, ApplicationContext容器初始化中refresh()中调用");
    }
}

3.BeanPostProcessor类

package com.fcc.spring.test;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/** * Created by fuchaochao on 16/8/12. */
public class InitBeanPostProcessor implements BeanPostProcessor { 
   
    public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
        System.out.println("8.postProcessBeforeInitialization(BeanPostProcessor), bean = " + o.getClass());
        return o;
    }

    public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
        System.out.println("12.postProcessAfterInitialization(BeanPostProcessor), bean = " + o.getClass());
        return o;
    }
}

4.InstantiationAwareBeanPostProcessor类

package com.fcc.spring.test;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;

import java.beans.PropertyDescriptor;
import java.util.Arrays;

/** * Created by fuchaochao on 16/8/12. */
public class InstanceBeanPostProcessor implements InstantiationAwareBeanPostProcessor { 
   
    public Object postProcessBeforeInstantiation(Class<?> aClass, String s) throws BeansException {
        System.out.println("2.实例化bean之前调用,即调用bean类构造函数之前调用 " + aClass.getName());
        /*try { return Class.forName(""+aClass); } catch (ClassNotFoundException e) { e.printStackTrace(); }*/
        return null;//其实我不是很明白这里返回值得作用,之后可能会去深入理解
    }

    public boolean postProcessAfterInstantiation(Object o, String s) throws BeansException {
        System.out.println("4.返回boolean,bean实例化后调用,并且返回false则不会注入属性");
        return true;
    }

    public PropertyValues postProcessPropertyValues(PropertyValues propertyValues, PropertyDescriptor[] propertyDescriptors, Object o, String s) throws BeansException {
        System.out.println("5.postProcessPropertyValues,在属性注入之前调用...... beanName = " + s + " 属性名集合 : " + Arrays.toString(propertyValues.getPropertyValues()));
        //System.out.println("message = " + ((HelloWorld)o).getMessage()); 这里可以看到message还是null
        return propertyValues;//这里要返回propertyValues,否则属性无法注入
    }

    public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
        System.out.println("9.postProcessBeforeInitialization(InstantiationAwareBeanPostProcessor) ");
        return o;
    }

    public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
        System.out.println("13.postProcessAfterInitialization(InstantiationAwareBeanPostProcessor) ");
        return o;
    }
}

5.测试类SpringTest2

package com.fcc.spring.test;

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

/** * Created by fuchaochao on 16/8/12. */
public class SpringTest2 { 
   
    public static void main(String[] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:config/spring/local/appcontext-*.xml");
        HelloWorld obj = (HelloWorld)context.getBean("helloWorld");
        System.out.println("14.Bean working, message = " + obj.getMessage());
        //((ClassPathXmlApplicationContext)context).refresh();
        ((ClassPathXmlApplicationContext)context).close();
    }
}

6.Spring Bean配置文件appcontext-service.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" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd ">

   <context:component-scan base-package="com.fcc.spring.test.*" />

    <bean id="helloWorld" class="com.fcc.spring.test.HelloWorld" init-method="xml_init" destroy-method="xml_destroy">
        <property name="message" value="Hello World!" />
    </bean>

    <bean class="com.fcc.spring.test.InitBeanPostProcessor" />
    <bean class="com.fcc.spring.test.InstanceBeanPostProcessor" />
    <bean class="com.fcc.spring.test.BeanFactoryPostProcessorTest" />
</beans>

7.结果代码:

八月 12, 2016 5:19:48 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@27b4fe4d: startup date [Fri Aug 12 17:19:48 CST 2016]; root of context hierarchy
八月 12, 2016 5:19:48 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from file [/Users/fuchaochao/joy/spring-test2/target/classes/config/spring/local/appcontext-service.xml]
1.postProcessBeanFactory(BeanFactoryPostProcessor) 工厂后处理器, ApplicationContext容器初始化中refresh()中调用
2.实例化bean之前调用,即调用bean类构造函数之前调用 com.fcc.spring.test.HelloWorld
3.HelloWorld struct.......
4.返回boolean,bean实例化后调用,并且返回false则不会注入属性
5.postProcessPropertyValues,在属性注入之前调用...... beanName = helloWorld 属性名集合 : [bean property 'message']
八月 12, 2016 5:19:48 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3ae4cdc3: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,helloWorld,com.fcc.spring.test.InitBeanPostProcessor#0,com.fcc.spring.test.InstanceBeanPostProcessor#0,com.fcc.spring.test.BeanFactoryPostProcessorTest#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
6.setBeanName(BeanNameAware) 属性注入后调用, 此时s = helloWorld
7.setBeanFactory(BeanFactory) setBeanName后调用
8.postProcessBeforeInitialization(BeanPostProcessor), bean = class com.fcc.spring.test.HelloWorld
9.postProcessBeforeInitialization(InstantiationAwareBeanPostProcessor) 
10.afterPropertiesSet(InitializingBean) processBeforeInitialization之后,配置的xml_init之前调用
11.HelloWorld 初始化(init-method) 12.postProcessAfterInitialization(BeanPostProcessor), bean = class com.fcc.spring.test.HelloWorld 13.postProcessAfterInitialization(InstantiationAwareBeanPostProcessor) 14.Bean working, message = Hello World! 八月 12, 2016 5:19:48 下午 org.springframework.context.support.AbstractApplicationContext doClose
15.destroy(DisposableBean) 在processAfterInitialization之后,配置的xml_destroy之前调用
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@27b4fe4d: startup date [Fri Aug 12 17:19:48 CST 2016]; root of context hierarchy
16.HelloWorld 销毁(destroy-method) 八月 12, 2016 5:19:48 下午 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
信息: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3ae4cdc3: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,helloWorld,com.fcc.spring.test.InitBeanPostProcessor#0,com.fcc.spring.test.InstanceBeanPostProcessor#0,com.fcc.spring.test.BeanFactoryPostProcessorTest#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy

Process finished with exit code 0

结果代码的详细解析查看下一节:Spring IoC初始化到Bean应用到容器销毁全过程。

总结

bean生命周期流程图:
这里写图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/191830.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • latex中希腊字母_LaTeX怎么念

    latex中希腊字母_LaTeX怎么念日常写论文,ppt作汇报等,经常需要编写公式,为方便查阅希腊字母对应latex表示,特写此表格,以便大家查阅。小写 Latex表示 大写 Latex表示 \alpha A A \beta B B \gamma \Gamma \delta \Delta \epsilon …

    2022年10月13日
    2
  • vue的双向绑定原理_数据双向绑定原理

    vue的双向绑定原理_数据双向绑定原理Vue双向绑定原理入门双向绑定概念数据可观测依赖收集完整示例总结从开始学习前端到现在走在进入中高级前端开发的路上,觉得上手容易又简单的就是Vue框架,包含其相关的生态系统。一直只是简单了解双向绑定的原理,并没有手动去实现或者去拜读过源码。而vue双向绑定基本是面试必考项,通过这段时间的学习,输出以下双向绑定的简单实现示例。参考文章:通俗易懂了解Vue双向绑定原理及实现双向绑定概念概念:…

    2022年10月7日
    2
  • 经典十大排序算法(含升序降序,基数排序含负数排序)【Java版完整代码】【建议收藏系列】[通俗易懂]

    经典十大排序算法(含升序降序,基数排序含负数排序)【Java版完整代码】【建议收藏系列】[通俗易懂]经典十大排序算法【Java版完整代码】写在前面的话十大排序算法对比冒泡排序快速排序直接选择排序堆排序归并排序插入排序希尔排序计数排序桶排序基数排序写在前面的话       虽然已经有很多人总结过这十大排序算法,优秀的文章也不少,但是Java完整版的好像不多,还存在某些文章代码存在错误的情况,同时也为了自己练手,决定把所有的写一遍巩固下,同时也真诚的希望阅读到这篇文章的小伙伴们可以自己去从头敲一遍,不要粘贴复制!希望我的文章对你有所帮助

    2022年6月11日
    27
  • 为什么大家都用i标签<i></i>用作小图标?[通俗易懂]

    为什么大家都用i标签<i></i>用作小图标?[通俗易懂]用<i>元素做图标在语义上是不正确的(虽然看起来像icon的缩写);<i>比<span>短,但gzip后差异很小,不过打字可以少按三个键;多数

    2022年8月2日
    11
  • redis的5种数据类型「建议收藏」

    redis的5种数据类型「建议收藏」1.redis的5种数据类型:string字符串(可以为整形、浮点型和字符串,统称为元素)list列表(实现队列,元素不唯一,先入先出原则)set集合(各不相同的元素)hashhash散列值(hash的key必须是唯一的)sortset有序集合2.string类型的常用命令:自加:incr

    2022年6月16日
    33
  • opacity属性的应用

    opacity属性的应用opacity是CSS中很有意思的属性,类似于Photoshop中不透明度的更改,结合绝对定位能实现很多漂亮的效果。opacity取值范围为0-1,若实现对IE浏览器的兼容,一般写为filter: alpha(opacity=XX);

    2022年5月9日
    39

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号