Spring Bean的生命周期(非常详细)

article/2025/8/24 3:16:42

生命周期图
在这里插入图片描述

文章目录

  • 前言
  • 一、生命周期流程图:
  • 二、各种接口方法分类
  • 三、演示

前言

Spring作为当前Java最流行、最强大的轻量级框架,受到了程序员的热烈欢迎。准确的了解Spring Bean的生命周期是非常必要的。我们通常使用ApplicationContext作为Spring容器。这里,我们讲的也是 ApplicationContext中Bean的生命周期。而实际BeanFactory也是差不多的,只不过处理器需要手动注册。

一、生命周期流程图:

Spring Bean的完整生命周期从创建Spring容器开始,直到最终Spring容器销毁Bean,这其中包含了一系列关键点。
在这里插入图片描述
在这里插入图片描述
若容器注册了以上各种接口,程序那么将会按照以上的流程进行。下面将仔细讲解各接口作用。

二、各种接口方法分类

Bean的完整生命周期经历了各种方法调用,这些方法可以划分为以下几类:

1、Bean自身的方法  :  这个包括了Bean本身调用的方法和通过配置文件中的init-method和destroy-method指定的方法

2、Bean级生命周期接口方法  :  这个包括了BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean这些接口的方法

3、容器级生命周期接口方法  :  这个包括了InstantiationAwareBeanPostProcessor 和 BeanPostProcessor 这两个接口实现,一般称它们的实现类为“后处理器”。

4、工厂后处理器接口方法  :  这个包括了AspectJWeavingEnabler, ConfigurationClassPostProcessor, CustomAutowireConfigurer等等非常有用的工厂后处理器  接口的方法。工厂后处理器也是容器级的。在应用上下文装配配置文件之后立即调用。

三、演示

我们用一个简单的Spring Bean来演示一下Spring Bean的生命周期。
1、首先是一个简单的Spring Bean,调用Bean自身的方法和Bean级生命周期接口方法,为了方便演示,它实现了BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean这4个接口,同时有2个方法,对应配置文件中的init-method和destroy-method。如下:

package springBeanTest;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;/*** @author qsk*/
public class Person implements BeanFactoryAware, BeanNameAware,InitializingBean, DisposableBean {private String name;private String address;private int phone;private BeanFactory beanFactory;private String beanName;public Person() {System.out.println("【构造器】调用Person的构造器实例化");}public String getName() {return name;}public void setName(String name) {System.out.println("【注入属性】注入属性name");this.name = name;}public String getAddress() {return address;}public void setAddress(String address) {System.out.println("【注入属性】注入属性address");this.address = address;}public int getPhone() {return phone;}public void setPhone(int phone) {System.out.println("【注入属性】注入属性phone");this.phone = phone;}@Overridepublic String toString() {return "Person [address=" + address + ", name=" + name + ", phone="+ phone + "]";}// 这是BeanFactoryAware接口方法@Overridepublic void setBeanFactory(BeanFactory arg0) throws BeansException {System.out.println("【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()");this.beanFactory = arg0;}// 这是BeanNameAware接口方法@Overridepublic void setBeanName(String arg0) {System.out.println("【BeanNameAware接口】调用BeanNameAware.setBeanName()");this.beanName = arg0;}// 这是InitializingBean接口方法@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("【InitializingBean接口】调用InitializingBean.afterPropertiesSet()");}// 这是DiposibleBean接口方法@Overridepublic void destroy() throws Exception {System.out.println("【DiposibleBean接口】调用DiposibleBean.destory()");}// 通过<bean>的init-method属性指定的初始化方法public void myInit() {System.out.println("【init-method】调用<bean>的init-method属性指定的初始化方法");}// 通过<bean>的destroy-method属性指定的初始化方法public void myDestory() {System.out.println("【destroy-method】调用<bean>的destroy-method属性指定的初始化方法");}
}

2、接下来是演示BeanPostProcessor接口的方法,如下:

package springBeanTest;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;public class MyBeanPostProcessor implements BeanPostProcessor {public MyBeanPostProcessor() {super();System.out.println("这是BeanPostProcessor实现类构造器!!");// TODO Auto-generated constructor stub}@Overridepublic Object postProcessAfterInitialization(Object arg0, String arg1)throws BeansException {System.out.println("BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!");return arg0;}@Overridepublic Object postProcessBeforeInitialization(Object arg0, String arg1)throws BeansException {System.out.println("BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!");return arg0;}
}

如上,BeanPostProcessor接口包括2个方法postProcessAfterInitialization和postProcessBeforeInitialization,这两个方法的第一个参数都是要处理的Bean对象,第二个参数都是Bean的name。返回值也都是要处理的Bean对象。这里要注意。
3、InstantiationAwareBeanPostProcessor 接口本质是BeanPostProcessor的子接口,一般我们继承Spring为其提供的适配器类InstantiationAwareBeanPostProcessor Adapter来使用它,如下:

package springBeanTest;import java.beans.PropertyDescriptor;import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;public class MyInstantiationAwareBeanPostProcessor extendsInstantiationAwareBeanPostProcessorAdapter {public MyInstantiationAwareBeanPostProcessor() {super();System.out.println("这是InstantiationAwareBeanPostProcessorAdapter实现类构造器!!");}// 接口方法、实例化Bean之前调用@Overridepublic Object postProcessBeforeInstantiation(Class beanClass,String beanName) throws BeansException {System.out.println("InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法");return null;}// 接口方法、实例化Bean之后调用@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName)throws BeansException {System.out.println("InstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法");return bean;}// 接口方法、设置某个属性时调用@Overridepublic PropertyValues postProcessPropertyValues(PropertyValues pvs,PropertyDescriptor[] pds, Object bean, String beanName)throws BeansException {System.out.println("InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法");return pvs;}
}

这个有3个方法,其中第二个方法postProcessAfterInitialization就是重写了BeanPostProcessor的方法。第三个方法postProcessPropertyValues用来操作属性,返回值也应该是PropertyValues对象。
4、演示工厂后处理器接口方法,如下:

package springBeanTest;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {public MyBeanFactoryPostProcessor() {super();System.out.println("这是BeanFactoryPostProcessor实现类构造器!!");}@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory arg0)throws BeansException {System.out.println("BeanFactoryPostProcessor调用postProcessBeanFactory方法");BeanDefinition bd = arg0.getBeanDefinition("person");bd.getPropertyValues().addPropertyValue("phone", "110");}}

5、配置文件如下beans.xml,很简单,使用ApplicationContext,处理器不用手动注册:

<?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:p="http://www.springframework.org/schema/p"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"><bean id="beanPostProcessor" class="springBeanTest.MyBeanPostProcessor"></bean><bean id="instantiationAwareBeanPostProcessor" class="springBeanTest.MyInstantiationAwareBeanPostProcessor"></bean><bean id="beanFactoryPostProcessor" class="springBeanTest.MyBeanFactoryPostProcessor"></bean><bean id="person" class="springBeanTest.Person" init-method="myInit"destroy-method="myDestory" scope="singleton" p:name="张三" p:address="广州"p:phone="15900000000" /></beans>

6、下面测试一下:

package springBeanTest;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class BeanLifeCycle {public static void main(String[] args) {System.out.println("现在开始初始化容器");ApplicationContext factory = new ClassPathXmlApplicationContext("springBeanTest/beans.xml");System.out.println("容器初始化成功");    //得到Preson,并使用Person person = factory.getBean("person",Person.class);System.out.println(person);System.out.println("现在开始关闭容器!");((ClassPathXmlApplicationContext)factory).registerShutdownHook();}
}

关闭容器使用的是实际是AbstractApplicationContext的钩子方法。

我们来看一下结果:

现在开始初始化容器
2014-5-18 15:46:20 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@19a0c7c: startup date [Sun May 18 15:46:20 CST 2014]; root of context hierarchy
2014-5-18 15:46:20 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [springBeanTest/beans.xml]
这是BeanFactoryPostProcessor实现类构造器!!
BeanFactoryPostProcessor调用postProcessBeanFactory方法
这是BeanPostProcessor实现类构造器!!
这是InstantiationAwareBeanPostProcessorAdapter实现类构造器!!
2014-5-18 15:46:20 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@9934d4: defining beans [beanPostProcessor,instantiationAwareBeanPostProcessor,beanFactoryPostProcessor,person]; root of factory hierarchy
InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法
【构造器】调用Person的构造器实例化
InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法
【注入属性】注入属性address
【注入属性】注入属性name
【注入属性】注入属性phone
【BeanNameAware接口】调用BeanNameAware.setBeanName()
【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()
BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!
【InitializingBean接口】调用InitializingBean.afterPropertiesSet()
【init-method】调用<bean>的init-method属性指定的初始化方法
BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!
InstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法
容器初始化成功
Person [address=广州, name=张三, phone=110]
现在开始关闭容器!
【DiposibleBean接口】调用DiposibleBean.destory()
【destroy-method】调用<bean>的destroy-method属性指定的初始化方法

http://chatgpt.dhexx.cn/article/D58OPxe1.shtml

相关文章

Spring 中Bean的生命周期

目录 Bean的生命周期 五个阶段 下面是一个bean对象创建到销毁经历过的方法。 图示​ 问答 普通Java类是在哪一步变成beanDefinition的 推荐视频&#xff1a; 阿里专家耗时一年&#xff0c;终于把Spring源码AOP、IOC、Ben生命周期、事物、设计模式以及循环依赖讲全了_哔哩…

Spring之Bean的生命周期详解

通过前面多个接口的介绍了解了Bean对象生命周期相关的方法&#xff0c;本文就将这些接口的方法串起来&#xff0c;来了解Bean的完整的生命周期。而介绍Bean的生命周期也是面试过程中经常会碰到的一个问题&#xff0c;如果不注意就跳坑里啦~~ Spring之Bean对象的初始化和销毁方法…

Bean的生命周期及演示

文章目录 一、介绍概念Bean生命周期组成&#xff1a; 二、实例演示 一、介绍 概念 Bean的生命周期是指一个Bean对象从创建到销毁的整个存在过程。 Bean生命周期组成&#xff1a; 1.实例化Bean&#xff08;为Bean分配内存空间&#xff09; 2.属性注入 (Bean注入和装配) 3.Bean…

面试题:Spring Bean的生命周期

最近在复习Spring的面试题&#xff0c;关于Spring Bean的生命周期一直没有很深入的理解&#xff0c;自己结合源码参考了网上的几篇文章&#xff0c;写了一点东西&#xff0c;方便理解。 Spring 启动&#xff0c;查找并加载需要被 Spring 管理的 Bean&#xff0c;进行 Bean 的…

Bean的生命周期和作用域

Bean的生命周期 Bean的执行流程&#xff1a; Bean 执行流程&#xff1a;启动Spring 容器 -> 实例化 Bean&#xff08;分配内存空间&#xff0c;从无到有&#xff09;-> Bean 注册到 Spring 中&#xff08;存操作&#xff09; -> 将 Bean 装配到需要的类中&#xff08;…

关于Spring Bean的生命周期

一、简介 Spring Bean 的生命周期在整个 Spring 中占有很重要的位置&#xff0c;从BeanFactory或ApplicationContext取得的实例为Singleton&#xff0c;也就是预设为每一个Bean的别名只能维持一个实例&#xff0c;而不是每次都产生一个新的对象使用Singleton模式产生单一实…

7、Bean的生命周期

Spring其实就是一个管理Bean对象的工厂。它负责对象的创建&#xff0c;对象的销毁等。 所谓的生命周期就是&#xff1a;对象从创建开始到最终销毁的整个过程。 什么时候创建Bean对象&#xff1f; 创建Bean对象的前后会调用什么方法&#xff1f; Bean对象什么时候销毁&#…

【一篇搞懂】 bean的生命周期详解

概述 Spring中的一个Bean从生到灭要经历很多过程,总体分为Bean定义、实例化、属性赋值(依赖注入)、初始化、生存期、销毁几个阶段: ​​​​​​​​ 下面是一个细化的Bean生命周期图: 过程比较复杂,重点关注Bean的定义、初始化、销毁过程,可以抓住重点: BeanPostPro…

Bean 生命周期详解

Spring Bean 的生命周期&#xff0c;面试时非常容易问&#xff0c;这不&#xff0c;前段时间就有个粉丝去字节面试&#xff0c;因为不会回答这个问题&#xff0c;一面都没有过。 如果只讲基础知识&#xff0c;感觉和网上大多数文章没有区别&#xff0c;但是我又想写得稍微深入…

【Spring】Spring的Bean的生命周期

作者简介&#xff1a;大家好&#xff0c;我是五度鱼&#xff0c;一个普通的Java领域博主&#xff0c;不停输出Java技术博客和干货。座右铭&#xff1a;锲而不舍&#xff0c;金石可镂。个人主页&#xff1a;五度鱼学Java的主页 文章目录 前言1. 什么是Bean的生命周期&#xff1f…

Spring中bean的生命周期(最详细)

Spring Bean的生命周期是Spring面试热点问题。Spring Bean的生命周期指的是从一个普通的Java类变成Bean的过程&#xff0c;深知Spring源码的人都知道这个给面试官讲的话大可讲30分钟以上&#xff0c;如果你不没有学习过Spring的源码&#xff0c;可能就知道Aware接口和调用init方…

Bean的生命周期

目录 一&#xff0c;bean的初始化 &#xff08;1&#xff09;Spring的IOC和AOP&#xff1a; &#xff08;2&#xff09;Spring Bean的生命周期&#xff1a; 二&#xff0c;单例模式与多例模式的区别 区别 《代码演示》 前言 回顾&#xff1a;Servlet的生命 初始化&#x…

bean的生命周期(最全最细讲解)

一、bean生命周期&#xff1a; 其定义为&#xff1a;从对象的创建到销毁的过程。而Spring中的一个Bean从开始到结束经历很多过程&#xff0c;但总体可以分为六个阶段Bean定义、实例化、属性赋值、初始化、生存期、销毁。 二、案例代码演示 1.首先我们来创建一个包&#xff0…

去字节面试,直接让人出门左拐:Bean 生命周期都不知道!

Spring Bean 的生命周期&#xff0c;面试时非常容易问&#xff0c;这不&#xff0c;前段时间就有个粉丝去字节面试&#xff0c;因为不会回答这个问题&#xff0c;一面都没有过。 如果只讲基础知识&#xff0c;感觉和网上大多数文章没有区别&#xff0c;但是我又想写得稍微深入…

Spring Bean生命周期,好像人的一生。。

大家好&#xff0c;我是老三&#xff0c;上节我们手撸了一个简单的IOC容器五分钟&#xff0c;手撸一个Spring容器&#xff01;&#xff0c;这节我们来看一看Spring中Bean的生命周期&#xff0c;我发现&#xff0c;和人的一生真的很像。 简单说说IoC和Bean IoC&#xff0c;控制…

Spring中bean的生命周期

Spring中的bean的生命周期主要包含四个阶段&#xff1a;实例化Bean --&#xff1e; Bean属性填充 --&#xff1e; 初始化Bean --&#xff1e;销毁Bean 首先是实例化Bean&#xff0c;当客户向容器请求一个尚未初始化的bean时&#xff0c;或初始化bean的时候需要注入另一个尚末初…

一文读懂 Spring Bean 的生命周期

欢迎大家关注我的微信公众号【老周聊架构】&#xff0c;Java后端主流技术栈的原理、源码分析、架构以及各种互联网高并发、高性能、高可用的解决方案。 一、前言 今天我们来说一说 Spring Bean 的生命周期&#xff0c;小伙伴们应该在面试中经常遇到&#xff0c;这是正常现象。…

ubuntu 换源深层次解析

换源也是一个容易出错的问题&#xff0c;本文以树莓派为例展开&#xff0c;x86也是一样的操作。 那么假设成立的话&#xff0c;就要记住我们是在树莓派&#xff08;arm&#xff09;上安装的ubuntu&#xff0c;不是X86&#xff0c;不是amd。 安装好系统后&#xff0c;我们第一…

[Linux]Ubuntu 换源 20.04 阿里源

注意&#xff0c;这篇文章其实不是简单的教你怎么换源&#xff0c;而是示例一种方法来换20.04的阿里源&#xff0c;其他源和版本大同小异。 笔者在写这篇文章的时候&#xff0c;20.04 还没有release出来正式版&#xff0c;但是已经可以在仓库里看到有源存在了&#xff0c;故写下…

Ubuntu换源详解,教你如何换源,并且解决常见的大坑

Ubuntu换源详解&#xff0c;教你如何换源&#xff0c;并且解决常见的大坑 记一次极不愉快的一次经历 首先注意&#xff0c;换源必须选择合适的版本&#xff0c;不可以在网上找一个下载源就直接去换 出现错误1&#xff1a; 由于没有公钥&#xff0c;无法验证下列签名 :NO_PUBK…