Spring bean的生命周期和扩展

接AnnotationConfigApplicationContext流程看实例化的beanPostProcessor-CSDN博客,以具体实例看bean生命周期的一些执行阶段

bean生命周期流程

生命周期扩展处理说明
实例化:createBeanInstance

构造方法, 如@Autowired的构造方法注入依赖bean

如UserService构造方法注入AppDAO:

@Autowired
public UserService(AppDAO appDAO) {System.out.println("@Autowired appDAO:" + appDAO);this.appDAO = appDAO;
}
属性设置:populateBean

如setter方法注入的依赖

如@Autoware的filed注入

如UserService中注入UserDAO:

@Resource(name = "u")
public void setUserDAO(UserDAO userDAO) {System.out.println("setUserDAO:" + userDAO);this.userDAO = userDAO;
}
初始化:initializeBean

1. BeanPostProcessor#postProcessBeforeInitialization

2. @PostConstruct

3. InitializingBean#afterPropertiesSet

initMethod

4. BeanPostProcessor#postProcessAfterInitialization

上一步骤属性设置完后,初始化方法前后都可以扩展。

例如BeanPostProcessor#postProcessBeforeInitialization,直接改变了set注入的appDAO对象

@Component
public class ServiceBeanPostProcessor implements BeanPostProcessor {@Overridepublic Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {// Bean 初始化前的逻辑if (beanName.equals("userService")) {UserService userService = (UserService)bean;AppDAO appDAO = new AppDAOImpl2();userService.setAppDAO(appDAO);System.out.println("postProcessBeforeInitialization:" + ":" + bean);}return bean;}
销毁

1. @PreDestroy

2. DisposableBean#destroy

destroyMethod

附org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean

/*** Actually create the specified bean. Pre-creation processing has already happened* at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.* <p>Differentiates between default bean instantiation, use of a* factory method, and autowiring a constructor.* @param beanName the name of the bean* @param mbd the merged bean definition for the bean* @param args explicit arguments to use for constructor or factory method invocation* @return a new instance of the bean* @throws BeanCreationException if the bean could not be created* @see #instantiateBean* @see #instantiateUsingFactoryMethod* @see #autowireConstructor*/protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)throws BeanCreationException {// Instantiate the bean.BeanWrapper instanceWrapper = null;if (mbd.isSingleton()) {instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);}if (instanceWrapper == null) {instanceWrapper = createBeanInstance(beanName, mbd, args);}final Object bean = instanceWrapper.getWrappedInstance();Class<?> beanType = instanceWrapper.getWrappedClass();if (beanType != NullBean.class) {mbd.resolvedTargetType = beanType;}// Allow post-processors to modify the merged bean definition.synchronized (mbd.postProcessingLock) {if (!mbd.postProcessed) {try {applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);}catch (Throwable ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,"Post-processing of merged bean definition failed", ex);}mbd.postProcessed = true;}}// Eagerly cache singletons to be able to resolve circular references// even when triggered by lifecycle interfaces like BeanFactoryAware.boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&isSingletonCurrentlyInCreation(beanName));if (earlySingletonExposure) {if (logger.isTraceEnabled()) {logger.trace("Eagerly caching bean '" + beanName +"' to allow for resolving potential circular references");}addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));}// Initialize the bean instance.Object exposedObject = bean;try {populateBean(beanName, mbd, instanceWrapper);exposedObject = initializeBean(beanName, exposedObject, mbd);}catch (Throwable ex) {if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {throw (BeanCreationException) ex;}else {throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);}}if (earlySingletonExposure) {Object earlySingletonReference = getSingleton(beanName, false);if (earlySingletonReference != null) {if (exposedObject == bean) {exposedObject = earlySingletonReference;}else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {String[] dependentBeans = getDependentBeans(beanName);Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);for (String dependentBean : dependentBeans) {if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {actualDependentBeans.add(dependentBean);}}if (!actualDependentBeans.isEmpty()) {throw new BeanCurrentlyInCreationException(beanName,"Bean with name '" + beanName + "' has been injected into other beans [" +StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +"] in its raw version as part of a circular reference, but has eventually been " +"wrapped. This means that said other beans do not use the final version of the " +"bean. This is often the result of over-eager type matching - consider using " +"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");}}}}// Register bean as disposable.try {registerDisposableBeanIfNecessary(beanName, bean, mbd);}catch (BeanDefinitionValidationException ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);}return exposedObject;}

扩展执行

接上文:AnnotationConfigApplicationContext流程看实例化的beanPostProcessor-CSDN博客,来看这些BeanPostProcessor如何起作用

测试bean定义类如下

@Service("userService")
public class UserService implements InitializingBean, DisposableBean {private String userServiceName;private UserDAO userDAO;private AppDAO appDAO;/*** field 注入*/@Autowiredprivate CommonService commonService;public UserService() {System.out.println("constructor");}/*** 类似于 InitializingBean 的 afterPropertiesSet() 方法*/@PostConstructpublic void init() {System.out.println("PostConstruct userService");System.out.println("userDAO is not null:" + (userDAO != null));System.out.println("appDAO is not null:" + (appDAO != null));userServiceName = "selfUserService";}/*** setter注入* @param userDAO*/@Resource(name = "u")public void setUserDAO(UserDAO userDAO) {System.out.println("setUserDAO:" + userDAO);this.userDAO = userDAO;}/*** 构造器注入* @param appDAO*/@Autowiredpublic UserService(AppDAO appDAO) {System.out.println("@Autowired appDAO:" + appDAO);this.appDAO = appDAO;}public void add(User user) {userDAO.save(user);}public UserDAO getUserDAO() {return userDAO;}/*** 类似于 DisposableBean 的 destroy() 方法*/@PreDestroypublic void preDestroy() {System.out.println("preDestroy");}@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("afterPropertiesSet userService");}@Overridepublic void destroy() throws Exception {System.out.println("destroy userService");}public void setUserServiceName(String userServiceName) {this.userServiceName = userServiceName;}public void setAppDAO(AppDAO appDAO) {this.appDAO = appDAO;}@Overridepublic String toString() {return "UserService{" +"userServiceName='" + userServiceName + '\'' +", userDAO=" + userDAO +", appDAO=" + appDAO +", commonService=" + commonService +'}';}
}

InstantiationAwareBeanPostProcessors:SmartInstantiationAwareBeanPostProcessor

推断构造函数,最后是AutowiredAnnotationBeanPostProcessor完成构造函数的推断

最后判断有@Autowired的构造函数 完成实例化过程

InstantiationAwareBeanPostProcessor:CommonAnnotationBeanPostProcessor

populate阶段CommonAnnotationBeanPostProcessor完成setter注入

/*** setter注入* @param userDAO*/
@Resource(name = "u")
public void setUserDAO(UserDAO userDAO) {System.out.println("setUserDAO:" + userDAO);this.userDAO = userDAO;
}

org.springframework.context.annotation.CommonAnnotationBeanPostProcessor#postProcessProperties

@Overridepublic PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {InjectionMetadata metadata = findResourceMetadata(beanName, bean.getClass(), pvs);try {metadata.inject(bean, beanName, pvs);}catch (Throwable ex) {throw new BeanCreationException(beanName, "Injection of resource dependencies failed", ex);}return pvs;}

InstantiationAwareBeanPostProcessor:AutowiredAnnotationBeanPostProcessor

populate阶段AutowiredAnnotationBeanPostProcessor完成@Autorwired的filed的注入,具体可以再次阅读:Spring5.1.3 @Autorwired注解原理重新回顾-CSDN博客

BeanPostProcessor#postProcessBeforeInitialization

initializeBean阶段会执行BeanPostProcessor的postProcessBeforeInitialization方法
执行自定义的BeanPostProcessor

执行CommonAnnotationBeanPostProcessor解析@PostConstruct注解

@PostConstruct
public void init() {System.out.println("PostConstruct userService");System.out.println("userDAO is not null:" + (userDAO != null));System.out.println("appDAO is not null:" + (appDAO != null));userServiceName = "selfUserService";
}

执行InitializingBean的afterPropertiesSet方法

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeInitMethods

protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)throws Throwable {boolean isInitializingBean = (bean instanceof InitializingBean);if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {if (logger.isTraceEnabled()) {logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");}if (System.getSecurityManager() != null) {try {AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {((InitializingBean) bean).afterPropertiesSet();return null;}, getAccessControlContext());}catch (PrivilegedActionException pae) {throw pae.getException();}}else {((InitializingBean) bean).afterPropertiesSet();}}if (mbd != null && bean.getClass() != NullBean.class) {String initMethodName = mbd.getInitMethodName();if (StringUtils.hasLength(initMethodName) &&!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&!mbd.isExternallyManagedInitMethod(initMethodName)) {invokeCustomInitMethod(beanName, bean, mbd);}}}
BeanPostProcessor#postProcessAfterInitialization

InitializingBean最后阶段会执行BeanPostProcessor的postProcessAfterInitialization方法

本例

@Component
public class ServiceBeanPostProcessor implements BeanPostProcessor {@Overridepublic Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {// Bean 初始化前的逻辑if (beanName.equals("userService")) {UserService userService = (UserService)bean;AppDAO appDAO = new AppDAOImpl2();userService.setAppDAO(appDAO);System.out.println("postProcessBeforeInitialization:" + ":" + bean);}return bean;}@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {// Bean 初始化后的逻辑if (beanName.equals("userService")) {System.out.println("postProcessAfterInitialization:" + ":" + bean);}return bean;}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/1378.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Rust】引用与借用

目录 思维导图 1. 引用与借用的基本概念 1.1. 引用示例 2. 借用的规则 2.1. 可变借用示例 2.2. 借用的限制 3. 引用的生命周期 思维导图 1. 引用与借用的基本概念 引用的定义&#xff1a;引用是一种指向数据的指针&#xff0c;但与裸指针不同&#xff0c;Rust的引用在编…

Java内存与缓存

Java内存管理和缓存机制是构建高性能应用程序的关键要素。它们之间既有联系又有区别&#xff0c;理解这两者对于优化Java应用至关重要。 Java 内存模型 Java内存模型&#xff08;JMM&#xff09;定义了线程如何以及何时可以看到其他线程修改过的共享变量的值&#xff0c;并且规…

java项目之智慧农贸信息化管理平台(ssm+mybatis+mysql)

风定落花生&#xff0c;歌声逐流水&#xff0c;大家好我是风歌&#xff0c;混迹在java圈的码农一枚。今天要和大家聊的是一款基于ssm的智慧农贸信息化管理平台。项目源码以及部署相关请联系风歌&#xff0c;文末附上联系信息 。 项目简介&#xff1a; 智慧农贸信息化管理平台…

java人脸识别

文章目录 前言 为什么选择虹软呢&#xff1f; 注册虹软账号&#xff0c;下载SDK 将jar包安装到maven本地仓库 项目实战 导入jar包 编写配置文件 Service 编写测试类 人脸识别更多应用 前言 ‌虹软人脸识别技术‌是由虹软公司开发的一系列人脸识别技术&#xff0c;包括…

【学习路线】Python自动化运维 详细知识点学习路径(附学习资源)

学习本路线内容之前&#xff0c;请先学习Python的基础知识 其他路线&#xff1a; Python基础 >> Python进阶 >> Python爬虫 >> Python数据分析&#xff08;数据科学&#xff09; >> Python 算法&#xff08;人工智能&#xff09; >> Pyth…

Nginx代理同域名前后端分离项目的完整步骤

前后端分离项目&#xff0c;前后端共用一个域名。通过域名后的 url 前缀来区别前后端项目。 以 vue php 项目为例。直接上 server 模块的 nginx 配置。 server{ listen 80; #listen [::]:80 default_server ipv6onlyon; server_name demo.com;#二配置项目域名 index index.ht…

73.矩阵置零 python

矩阵置零 题目题目描述示例 1&#xff1a;示例 2&#xff1a;提示&#xff1a; 题解思路分析Python 实现代码代码解释提交结果 题目 题目描述 给定一个 m x n 的矩阵&#xff0c;如果一个元素为 0 &#xff0c;则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。 示例…

【深度学习】通俗理解偏差(Bias)与方差(Variance)

在统计学习中&#xff0c;我们通常使用方差与偏差来衡量一个模型 1. 方差与偏差的概念 偏差(Bais)&#xff1a; 预测值和真实值之间的误差 方差(Variance)&#xff1a; 预测值之间的离散程度 低偏差低方差、高偏差低方差&#xff1a; 图中每个点表示同一个模型每次采样出不同…

Git学习记录

针对各个项目的gitignore文件示例 github/gitignore: A collection of useful .gitignore templates 忽略文件 文件 .gitignore 的格式规范如下&#xff1a; • 所有空行或者以 &#xff03; 开头的行都会被 Git 忽略。 • 可以使用标准的 glob 模式匹配。 • 匹配模式…

自然语言转 SQL:通过 One API 将 llama3 模型部署在 Bytebase SQL 编辑器

使用 Open AI 兼容的 API&#xff0c;可以在 Bytebase SQL 编辑器中使用自然语言查询数据库。 出于数据安全的考虑&#xff0c;私有部署大语言模型是一个较好的选择 – 本文选择功能强大的开源模型 llama3。 由于 OpenAI 默认阻止出站流量&#xff0c;为了简化网络配置&#…

Cookie和Session

会话&#xff1a; 有状态会话&#xff1a; 客户端知道发起请求的是谁 无状态会话&#xff1a; 不知道发起请求的是谁 只知道有请求 http是无状态请求 保存会话信息的两种技术&#xff1a; 可以通过Cookie和Session储存会话信息 cookie&#xff1a;客户端技术 信心存…

ImportError: attempted relative import with no known parent package 报错的解决!

本人在做调用超级鹰API解决点触验证码时&#xff0c;两次出现本报错。研究后解决&#xff0c;步骤如下&#xff1a;&#xff08;注意&#xff1a;如果项目目录结构简单且无中文目录&#xff0c;直接使用绝对路径即可解决&#xff01;&#xff01;&#xff01;&#xff09; 1.项…

介绍下不同语言的异常处理机制

Golang 在Go语言中&#xff0c;有两种用于处于异常的机制&#xff0c;分别是error和panic&#xff1b; panic panic 是 Go 中处理异常情况的机制&#xff0c;用于表示程序遇到了无法恢复的错误&#xff0c;需要终止执行。 使用场景 程序出现严重的不符合预期的问题&#x…

使用gtsam添加OrientedPlane3Factor平面约束因子

在基于地面约束的SLAM优化中&#xff0c;已知的地面信息&#xff08;如 plan.pcd 文件中的地面模型&#xff09;可以用作一个先验约束&#xff0c;以帮助优化位姿估计。具体而言&#xff0c;这个过程涉及将地面模型和每个帧的位姿结合&#xff0c;以创建一个因子模型&#xff0…

Cython全教程2 多种定义方式

—— 本篇文章&#xff0c;主要讲述Cython中的四种定义关键字 全教程2 多种定义方式&#xff1a; 在Cython中&#xff0c;关于定义的关键字有四个&#xff0c;分别是&#xff1a; cdef、def、cpdef、DEF 一、cdef定义关键字 顾名思义&#xff0c;cdef关键字定义的是一个C函数…

WINFORM - DevExpress -> DevExpress总结[安装、案例]

安装devexpress软件 路径尽量不换&#xff0c;后面破解不容易出问题 vs工具箱添加控件例如: ①使用控制台进入DevExpress安装目录: cd C:\Program Files (x86)\DevExpress 20.1\Components\Tools ②添加DevExpress控件&#xff1a; ToolboxCreator.exe/ini:toolboxcreator…

primitive 的 Appearance编写着色器材质

import { nextTick, onMounted, ref } from vue import * as Cesium from cesium import gsap from gsaponMounted(() > { ... })// 1、创建矩形几何体&#xff0c;Cesium.RectangleGeometry&#xff1a;几何体&#xff0c;Rectangle&#xff1a;矩形 let rectGeometry new…

《JavaWeb开发-javascript基础》

文章目录 《JavaWeb开发-javascript基础》1.javascript 引入方式2.JS-基础语法-书写语法2.1 书写语法2.2 输出语句 3.JS-基础语法-变量4.JS-基础语法-数据类型&运算符4.1 数据类型4.2 运算符4.3 数据类型转换 5. JS-函数6. JS-对象-Array数组7. JS-对象-String字符串8. JS-…

从CentOS到龙蜥:企业级Linux迁移实践记录(龙蜥开局)

引言&#xff1a; 在我们之前的文章中&#xff0c;我们详细探讨了从CentOS迁移到龙蜥操作系统的基本过程和考虑因素。今天&#xff0c;我们将继续这个系列&#xff0c;重点关注龙蜥系统的实际应用——特别是常用软件的安装和配置。 龙蜥操作系统&#xff08;OpenAnolis&#…

【python基础——异常BUG】

什么是异常(BUG) 检测到错误,py编译器无法继续执行,反而出现错误提示 如果遇到错误能继续执行,那么就捕获(try) 1.得到异常:try的执行,try内只可以捕获一个异常 2.预案执行:except后面的语句 3.传入异常:except … as uestcprint(uestc) 4.没有异常:else… 5.鉴定完毕,收尾的语…