Spring bean的生命周期和扩展

embedded/2025/1/16 0:50:29/

接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

java">/*** 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定义类如下

java">@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

java">@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

java">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.ppmy.cn/embedded/154251.html

相关文章

Python----Python爬虫(Scrapy的应用:CrawlSpider 使用,爬取小说,CrawlSpider版)

一、CrawlSpider 使用 1.1、CrawlSpider CrawSpiders 是 Scrapy 框架中的一个特殊爬虫类&#xff0c;它用于处理需要跟随链接并抓取多个页面的情况。相比于基本的 Spider 类&#xff0c;CrawSpiders 提供了一个更灵活、更强大的方式来定义爬取规则。 在Scrapy中Spider是所有爬…

easyui datagrid表头和网格错位问题

问题&#xff1a;表头与数据网格错位 解决&#xff1a; 在onLoadSuccess事件中调用fitColumns方法 $(this).datagrid(‘fitColumns’);

从零开始:在服务器上部署大模型并集成到 vscode +Cline使用

1. 引言 (Introduction) 欢迎来到本篇技术博客&#xff01; 在本文中&#xff0c; 我将引导你一步一步地在阿里云服务器上部署 Qwen 大模型&#xff0c;并将其集成到 Cline 插件中。 我们将从零开始&#xff0c;详细介绍每个步骤&#xff0c;确保即使是初学者也能轻松上手。 …

vue router的使用

一、引入 vue-router是Vue.js官方的路由插件&#xff0c;它和vue.js是深度集成的&#xff0c;适合用于构建单页面应用。vue的单页面应用是基于路由和组件的&#xff0c;路由用于设定访问路径&#xff0c;并将路径和组件映射起来。传统的页面应用&#xff0c;是用一些超链接来实…

K8S集群常用命令

1&#xff0c;查看pod kubectl get pods -A 查看所有的pod kubectl get pods 这个只查看namespace为default下的pod&#xff0c;也就是只查看默认命名空间下的pod kubectl get pod -A -o wide 查看所有的pod&#xff0c;并且放出的信息更全&#xff08;包含了pod的ip&#xff0…

Windows图形界面(GUI)-QT-C/C++ - QT框架解析

公开视频 -> 链接点击跳转公开课程博客首页 -> ​​​链接点击跳转博客主页 目录 工程配置 代码视图 配置文件 核心代码 工程配置 New Project QT Widgets Application 涉及到名称输入不要存在中文 QMAKE Weight 可以手动指定修改类文件 选择开发环境 代码视图 配置…

【Elasticsearch】批量操作:优化性能

🧑 博主简介:CSDN博客专家,历代文学网(PC端可以访问:https://literature.sinhy.com/#/?__c=1000,移动端可微信小程序搜索“历代文学”)总架构师,15年工作经验,精通Java编程,高并发设计,Springboot和微服务,熟悉Linux,ESXI虚拟化以及云原生Docker和K8s,热衷于探…

RuoYi-Vue-Plus 加入 GitCode:驱动多租户后台管理创新发展

在当今数字化进程持续推进的时代背景下&#xff0c;企业对后台管理系统的要求不断攀升&#xff0c;高效、安全、灵活与可拓展性成为关键要素。近日&#xff0c;RuoYi-Vue-Plus 正式加入 GitCode&#xff0c;为多租户后台管理领域带来全新动力与机遇&#xff0c;有力推动行业技术…