https://www.jianshu.com/p/1dec08d290c1

https://www.cnblogs.com/zrtqsk/p/3735273.html

总结

  1. 将class文件加载成BeanDefinition,并向IOC容器中进行注册
  2. 在实例化前,能通过实现BeanFactoryPostProcessor,进行BeanDefinition注册,设置Bean属性值等功能
  3. 在createBean时,实现SmartInstantiationAwareBeanPostProcessor或InstantiationAwareBeanPostProcessor接口的postProcessBeforeInstantiation的方法
  4. Bean 实例化(createBeanInstance)
  5. 实现InstantiationAwareBeanPostProcessor接口,在populateBean中调用postProcessAfterInstantiation
  6. initializeBean时,调用invokeAwareMethods(),实现类通过实现BeanFactoryAware, BeanNameAware进行自定义一些功能
  7. 实现BeanPostProcessor的postProcessBeforeInitialization()
  8. @PostConstruct
  9. invokeInitMethods反射方式进行初始化
  10. afterPropertiesSet(),初始化后进行属性设置
  11. BeanPostProcessor#postProcessAfterInitialization()
  12. @PreDestroy
  13. destroy()

加载成BeanDefinition,并向IOC容器中进行注册

详见前文《Spring源码之IOC容器创建、BeanDefinition加载和注册和IOC容器依赖注入》

BeanFactoryPostProcessor#invokeBeanFactoryPostProcessors()

在PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors()方法中完成invokeBeanDefinitionRegistryPostProcessors() BeanDefinition的注册后,会调用各BeanFactoryPostProcessor的postProcessBeanFactory方法,此时可自定义实现BeanFactoryPostProcessor的postProcessBeanFactory方法,进行属性添加等功能。

一个例子:

@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
int i = 1; public MyBeanFactoryPostProcessor() {
super();
System.out.println("这是BeanFactoryPostProcessor实现类构造器!!");
} @Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
throws BeansException { if(beanFactory.getBeanDefinition("person") != null && i == 1) {
i--;
System.out.println("BeanFactoryPostProcessor调用postProcessBeanFactory方法");
} BeanDefinition bd = beanFactory.getBeanDefinition("person");
bd.getPropertyValues().addPropertyValue("name", "Carl");
}
}
postProcessBeforeInstantiation()

在createBean时,实例化(Instantiation Bean)前,自定义实现SmartInstantiationAwareBeanPostProcessor接口的postProcessBeforeInstantiation的方法,可做一些自定义处理。

@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
......
}

一个例子:

@Component
public class MyInstantiationAwareBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor { // 接口方法、实例化Bean之前调用
@Override
public Object postProcessBeforeInstantiation(Class beanClass,String beanName) throws BeansException { if(beanName.equals("person")) {
System.out.println("InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法");
}
return null;
}
}
实例化时初始化构造器

由AbstractAutowireCapableBeanFactory#doCreateBean()入口,通过createBeanInstance去进行实例化

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
......
}

SimpleInstantiationStrategy#instantiate()

@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
......
return BeanUtils.instantiateClass(constructorToUse);
}
postProcessAfterInstantiation

在AbstractAutowireCapableBeanFactory#populateBean()中

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
...... // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
}
postProcessPropertyValues()
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {

		PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
if (pvsToUse == null) {
......
pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
......
}
pvs = pvsToUse;
}
}
}

例子:

@Component
public class MyInstantiationAwareBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor {
// 接口方法、设置某个属性时调用
@Override
public PropertyValues postProcessPropertyValues(PropertyValues pvs,PropertyDescriptor[] pds, Object bean, String beanName)
throws BeansException {
if(beanName.equals("person")) {
System.out.println("InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法");
} return pvs;
}
}
invokeAwareMethods()
private void invokeAwareMethods(String beanName, Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}

例子:

@Component
public class Person implements BeanFactoryAware, BeanNameAware,InitializingBean, DisposableBean {
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println("【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()");
this.beanFactory = beanFactory;
} // 这是BeanNameAware接口方法
@Override
public void setBeanName(String beanName) {
System.out.println("【BeanNameAware接口】调用BeanNameAware.setBeanName()");
this.beanName = beanName;
}
}
postProcessBeforeInitialization()

执行初始化

exposedObject = initializeBean(beanName, exposedObject, mbd);
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
......
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
}

一个例子:

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
if(beanName.equals("person")) {
System.out.println("BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!");
}
return bean;
}
}
@PostConstruct

InitDestroyAnnotationBeanPostProcessor#postProcessBeforeInitialization()

通过反射方式去调用@PostConstruct注解的方法

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
try {
metadata.invokeInitMethods(bean, beanName);
}
......
return bean;
}

例子:

@PostConstruct
public void myInit() {
System.out.println("【init-method】调用<bean>的init-method属性指定的初始化方法");
}
初始化(invokeInitMethods)

AbstractAutowireCapableBeanFactory#initializeBean()

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
try {
invokeInitMethods(beanName, wrappedBean, mbd);
}
}
afterPropertiesSet()

AbstractAutowireCapableBeanFactory#invokeInitMethods()

protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable { ((InitializingBean) bean).afterPropertiesSet();
.......
}
BeanPostProcessor#postProcessAfterInitialization()
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
......
}

例子:

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
if(beanName.equals("person")){
System.out.println("BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!");
} return bean;
}
}
@PreDestroy

在DisposableBeanAdapter#destroy()方法中,调用InitDestroyAnnotationBeanPostProcessor#postProcessBeforeDestruction(),最后通过反射执行@PreDestroy方法

@Override
public void destroy() {
if (!CollectionUtils.isEmpty(this.beanPostProcessors)) {
for (DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {
processor.postProcessBeforeDestruction(this.bean, this.beanName);
}
}
}

例子

@Component
public class Person implements BeanFactoryAware, BeanNameAware,InitializingBean, DisposableBean {
@PreDestroy
public void myDestory() {
System.out.println("【destroy-method】调用<bean>的destroy-method属性指定的初始化方法");
}
}
destroy
@Component
public class Person implements BeanFactoryAware, BeanNameAware,InitializingBean, DisposableBean {
@Override
public void destroy() throws Exception {
System.out.println("【DiposibleBean接口】调用DiposibleBean.destory()");
}
}

Spring源码之Bean生命周期的更多相关文章

  1. Spring源码系列 — Bean生命周期

    前言 上篇文章中介绍了Spring容器的扩展点,这个是在Bean的创建过程之前执行的逻辑.承接扩展点之后,就是Spring容器的另一个核心:Bean的生命周期过程.这个生命周期过程大致经历了一下的几个 ...

  2. Spring源码 21 Bean生命周期

    参考源 https://www.bilibili.com/video/BV1tR4y1F75R?spm_id_from=333.337.search-card.all.click https://ww ...

  3. Spring之BeanFactory及Bean生命周期

    1.spring通过BeanFactory灵活配置.管理bean,Spring对管理的bean没有任何特别的要求,完全支持对POJO的管理: 2.BeanFactory有个ApplicationCon ...

  4. 深入源码理解SpringBean生命周期

    概述 本文描述下Spring的实例化.初始化.销毁,整个SpringBean生命周期,聊一聊BeanPostProcessor的回调时机.Aware方法的回调时机.初始化方法的回调及其顺序.销毁方法的 ...

  5. Vue2.0源码阅读笔记--生命周期

    一.Vue2.0的生命周期 Vue2.0的整个生命周期有八个:分别是 1.beforeCreate,2.created,3.beforeMount,4.mounted,5.beforeUpdate,6 ...

  6. Laravel源码分析--Laravel生命周期详解

    一.XDEBUG调试 这里我们需要用到php的 xdebug 拓展,所以需要小伙伴们自己去装一下,因为我这里用的是docker,所以就简单介绍下在docker中使用xdebug的注意点. 1.在php ...

  7. angular11源码探索[DoCheck 生命周期和onChanges区别]

    网站 https://blog.thoughtram.io/ https://juristr.com/ https://www.concretepage.com/angular/ https://ww ...

  8. Spring BeanFactory 初始化 和 Bean 生命周期

    (version:spring-context-4.3.15.RELEASE) AbstractApplicationContext#refresh() public void refresh() t ...

  9. 【spring源码】bean的实例化(转载)

    首先来看一段代码,看过上一节的朋友肯定对这段代码并不陌生.这一段代码诠释了Spring加载bean的完整过程,包括读取配置文件,扫描包,加载类,实例化bean,注入bean属性依赖. 上一节介绍了Sp ...

随机推荐

  1. jmeter 相关

    Don't use GUI mode for load testing !, only for Test creation and Test debugging. For load testing, ...

  2. Windows 上的苹果 mac Time Machine 时间机器免费替代品 FreeFileSync 操作指南

    Windows 上的苹果 mac Time Machine 时间机器免费替代品 FreeFileSync 操作指南 前言:为什么不用 Windows 10 自带的备份还原呢?因为不稳定,不能很好的备份 ...

  3. ngx_align 值对齐宏

    ngx_align 值对齐宏 ngx_align 为nginx中的一个值对齐宏.主要在需要内存申请的地方使用,为了减少在不同的 cache line 中内存而生. // d 为需要对齐的 // a 为 ...

  4. HTML5/HTML 4.01/XHTML 元素和有效的 DTD

    HTML5/HTML 4.01/XHTML 元素和有效的 DTD 下面的表格列出了所有的 HTML5/HTML 4.01/XHTML 元素,以及它们会出现在什么文档类型 (DTD) 中: 标签 HTM ...

  5. 存储系列1-openfiler开源存储管理平台实践

    (一)openfiler介绍 Openfiler能把标准x86/64架构的系统变为一个更强大的NAS.SAN存储和IP存储网关,为管理员提供一个强大的管理平台,并能应付未来的存储需求.openfile ...

  6. 联赛模拟测试20 C. Weed

    题目描述 \(duyege\) 的电脑上面已经长草了,经过辨认上面有金坷垃的痕迹. 为了查出真相,\(duyege\) 准备修好电脑之后再进行一次金坷垃的模拟实验. 电脑上面有若干层金坷垃,每次只能在 ...

  7. 腾讯云服务器简单配置web项目

    如图:目前域名备案工作完成,需要将主页展示出来, 域名解析就不讲了,超级简单, 如果不理解可以加群交流,这里主要讲一下通过Apache 开启服务(80端口)对项目进行展示 1.  首先安装Apache ...

  8. MVC框架的代码审计小教程

    介绍 YxtCMF在线学习系统是一个以thinkphp+bootstrap为框架进行开发的网络学习平台系统. 在线学习系统,为现代学习型组织提供了卓有成效的学习与培训方案, 能够通过在线学习和在线评估 ...

  9. Educational Codeforces Round 97 (Rated for Div. 2)

    补了一场Edu round. A : Marketing Scheme 水题 #include <cstdio> #include <algorithm> typedef lo ...

  10. NB-IOT基站的优势和特点

    NB-IOT基站是什么        NB-IOT基站的主要目的是完成移动通信网和UE之间的通信和管理功能,在移动通信中是组成蜂窝小区最基本的单元.只有在基站信号的覆盖范围之内通过运营商网络连接的NB ...