Spring中Bean的生命周期管理

embedded/2024/9/24 2:21:26/

Spring框架中的Bean生命周期是指从创建到销毁的整个过程。在这个过程中,Spring容器会负责管理Bean的状态和行为。以下是Spring中Bean生命周期的详细解释:

  1. 实例化:Spring容器根据Bean的定义信息,通过反射机制创建Bean对象。

  2. 设置属性值:Spring容器会根据Bean定义中的配置信息,为Bean对象设置属性值。这包括依赖注入的过程。

  3. 调用BeanNameAware接口方法:如果Bean实现了BeanNameAware接口,Spring容器会调用setBeanName()方法,将Bean的名称传递给Bean。

  4. 调用BeanFactoryAware接口方法:如果Bean实现了BeanFactoryAware接口,Spring容器会调用setBeanFactory()方法,将BeanFactory实例传递给Bean。

  5. 调用ApplicationContextAware接口方法:如果Bean实现了ApplicationContextAware接口,Spring容器会调用setApplicationContext()方法,将ApplicationContext实例传递给Bean。

  6. 调用BeanPostProcessor的postProcessBeforeInitialization()方法:Spring容器会调用实现了BeanPostProcessor接口的类的postProcessBeforeInitialization()方法,对Bean进行预初始化处理。

  7. 调用InitializingBean接口方法:如果Bean实现了InitializingBean接口,Spring容器会调用afterPropertiesSet()方法,用于Bean的初始化操作。

  8. 调用自定义的初始化方法:如果在Bean定义中配置了init-method属性,Spring容器会调用指定的初始化方法。

  9. 调用BeanPostProcessor的postProcessAfterInitialization()方法:Spring容器会调用实现了BeanPostProcessor接口的类的postProcessAfterInitialization()方法,对Bean进行初始化后的处理。

  10. Bean可以被使用:此时Bean已经初始化完成,可以被应用程序正常使用。

  11. 调用DisposableBean接口方法:当容器关闭时,如果Bean实现了DisposableBean接口,Spring容器会调用destroy()方法,用于Bean的资源释放操作。

  12. 调用自定义的销毁方法:如果在Bean定义中配置了destroy-method属性,Spring容器会调用指定的销毁方法。

  13. 销毁Bean:Spring容器销毁Bean对象,释放内存资源。

总结一下,Spring中Bean的生命周期包括实例化、设置属性值、调用Aware接口方法、调用BeanPostProcessor的前后处理方法、调用InitializingBean和DisposableBean接口方法以及自定义的初始化和销毁方法。在这个过程中,Spring容器负责管理Bean的状态和行为。

以下为示例代码

MyBean

java">package org.example.bean01.ch01;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;@Component
public class MyBean implements ApplicationContextAware, BeanFactoryAware, BeanNameAware, InitializingBean, DisposableBean {private String name;private String address;private int phone;private String beanName;private BeanFactory beanFactory;private ApplicationContext context;// 通过<bean>的init-method属性指定的初始化方法public void myInit() {System.out.println("调用<bean>的init-method属性指定的初始化方法");}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.context = applicationContext;System.out.println("调用ApplicationContextAware.setApplicationContext接口");}public String show() {return this.toString();}public MyBean() {System.out.println("调用MyBean的构造器实例化");}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 "MyBean [address=" + address + ", name=" + name + ", phone=" + phone + "]";}// 这是BeanFactoryAware接口方法@Overridepublic void setBeanFactory(BeanFactory arg0) throws BeansException {System.out.println("调用BeanFactoryAware.setBeanFactory()");this.beanFactory = arg0;}// 这是BeanNameAware接口方法@Overridepublic void setBeanName(String arg0) {System.out.println("调用BeanNameAware.setBeanName()");this.beanName = arg0;}// 这是InitializingBean接口方法@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("调用InitializingBean.afterPropertiesSet()");}// 这是DiposibleBean接口方法@Overridepublic void destroy() throws Exception {System.out.println("调用DiposibleBean.destory()");}// 通过<bean>的destroy-method属性指定的初始化方法public void myDestory() {System.out.println("调用<bean>的destroy-method属性指定的初始化方法");}
}

MyBeanFactoryPostProcessor

java">package org.example.bean01.ch01;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;@Component
public class MyBean implements ApplicationContextAware, BeanFactoryAware, BeanNameAware, InitializingBean, DisposableBean {private String name;private String address;private int phone;private String beanName;private BeanFactory beanFactory;private ApplicationContext context;// 通过<bean>的init-method属性指定的初始化方法public void myInit() {System.out.println("调用<bean>的init-method属性指定的初始化方法");}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.context = applicationContext;System.out.println("调用ApplicationContextAware.setApplicationContext接口");}public String show() {return this.toString();}public MyBean() {System.out.println("调用MyBean的构造器实例化");}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 "MyBean [address=" + address + ", name=" + name + ", phone=" + phone + "]";}// 这是BeanFactoryAware接口方法@Overridepublic void setBeanFactory(BeanFactory arg0) throws BeansException {System.out.println("调用BeanFactoryAware.setBeanFactory()");this.beanFactory = arg0;}// 这是BeanNameAware接口方法@Overridepublic void setBeanName(String arg0) {System.out.println("调用BeanNameAware.setBeanName()");this.beanName = arg0;}// 这是InitializingBean接口方法@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("调用InitializingBean.afterPropertiesSet()");}// 这是DiposibleBean接口方法@Overridepublic void destroy() throws Exception {System.out.println("调用DiposibleBean.destory()");}// 通过<bean>的destroy-method属性指定的初始化方法public void myDestory() {System.out.println("调用<bean>的destroy-method属性指定的初始化方法");}
}

MyBeanPostProcessor

java">package org.example.bean01.ch01;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;public class MyBeanPostProcessor implements BeanPostProcessor {public MyBeanPostProcessor() {super();System.out.println("调用BeanPostProcessor实现类构造器");}@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;}
}

AppConfig

java">package org.example.bean01.ch01;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;@Configuration
@ComponentScan(basePackages = "org.example.bean01.ch01")
public class AppConfig {@Beanpublic MyBeanPostProcessor myBeanPostProcessor() {return new MyBeanPostProcessor();}@Beanpublic MyBeanFactoryPostProcessor myBeanFactoryPostProcessor() {return new MyBeanFactoryPostProcessor();}@Bean(initMethod = "myInit", destroyMethod = "myDestory")public MyBean myBean() {return new MyBean();}}

启动类BeanDemo

java">package org.example.bean01.ch01;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class BeanDemo {public static void main(String[] args) {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);MyBean myBean = context.getBean(MyBean.class);// 使用BeanSystem.out.println("Using bean: " + myBean.show());context.close();}
}

执行结果

在这里插入图片描述


http://www.ppmy.cn/embedded/101822.html

相关文章

【国产游戏的机遇与挑战】

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学…

8.23-docker基础命令学习

docker 1.docker容器 [rootdocker ~]# systemctl start docker[rootdocker ~]# docker imagesREPOSITORY TAG IMAGE ID CREATED SIZEcentos latest 5d0da3dc9764 2 years ago 231MB​# 容器执行完就退出了​[rootdocker ~]# docker run -it …

Python的起源与发展历程:从创意火花到全球热门编程语言

目录 创意的火花名字的由来圣诞节的礼物社区的力量今天的Python Python的起源可以追溯到1989年&#xff0c;当时荷兰计算机科学家Guido van Rossum&#xff08;吉多范罗苏姆&#xff09;在阿姆斯特丹的荷兰国家数学和计算机科学研究所&#xff08;CWI&#xff09;工作。Python的…

数据实体类主键使用UUID生成策略

方式一&#xff1a; 推荐 如果你使用的是JPA进行数据持久化操作的开发者&#xff0c;如何在实体类中配置UUID作为主键生成策略。通过Entity、Table、GenericGenerator和GeneratedValue等注解&#xff0c;可以实现自动为数据实体生成唯一的UUID主键&#xff0c;无需手动设…

LongWriter——从长文本语言模型中释放出10,000+字的生成能力

概述 当前的长上下文大型语言模型 (LLM) 可以处理多达 100,000 个词的输入&#xff0c;但它们很难生成超过 2,000 个词的输出。受控实验表明&#xff0c;该模型的有效生成长度本质上受到监督微调(SFT) 期间看到的示例的限制。换句话说&#xff0c;这种输出限制源于现有 SFT 数…

【网络编程】第十一章 数据链路层 - 以太网(MAC+MTU+ARP+MSS+RARP)

文章目录 重点链路层以太网MAC帧格式碰撞域MAC地址MAC地址和IP地址 MTU-最大传输单元MTU 对 IP 的影响MTU 对 UDP 的影响MTU 对 TCP 的影响-MSS ARP协议ARP协议的工作流程ARP请求的过程ARP应答的过程 ARP 缓存中间人攻击 RARP协议 重点 数据链路层的作用&#xff1a;两个设备 …

【ORACLE】decode() 函数

在Oracle数据库中&#xff0c;DECODE 函数是一个非常有用的条件表达式&#xff0c;它类似于其他编程语言中的 switch-case 或 if-else 语句。DECODE 函数可以简化查询中的条件逻辑&#xff0c;使得SQL语句更加简洁和易于理解。 基本语法 DECODE 函数的基本语法如下&#xff1…

Java将数据导出为Excel文件

使用Apache POI生成基本Excel Apache POI是一个强大的Java库&#xff0c;用来处理Microsoft Office文件。对于Excel文件&#xff08;.xls和.xlsx&#xff09;处理&#xff0c;提供有HSSF&#xff08;.xls&#xff09;和XSSF&#xff08;.xlsx&#xff09;等API。 import org.…