知识回顾

Bean的创建过程会经历getBeandoGetBeancreateBeandoCreateBean,然后Bean的创建又会经历实例化,属性填充,初始化。

在实例化createInstance时大致可以分为三种方式进行实例化:

  • 使用Supplier 进行实例化,通过BeanFactoryPostProcessorBeanDefinition进行修改,增加一个Supplier属性,放置一个lambda表达式用于创建对象
  • 使用factory-method进行实例化
    • 使用实例工厂实例化
    • 使用静态工厂实例化
  • 使用构造器反射进行实例化
    • 使用SmartInstantiationAwareBeanPostProcessor解析构造器,然后反射实例化
    • 使用无参构造器进行实例化

在属性填充populateBean时大致可以分为4个步骤:

  • 调用InstantiationAwareBeanPostProcessor接口的after方法修改Bean的信息
  • 自动装配,将解析的属性和属性值放入到pvs变量中
    • autowireByType自动装配
    • autowireByName自动装配
  • 执行通过CommonAnnotationBeanPostProcessorAtowiredAnnotationBeanPostProcessor解析的注解,然后注入到字段上
  • 对属性的值进行解析,解析pvs, 会涉及到参数转换,spel表达式解析,引用类型,String类型,List类型,Map类型,Set类型,Properties类型的解析,属性编辑器的解析等。

接下来解读初始化阶段

bean的初始化

bean的初始化initializeBean方法,直接上源码:

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
// 执行Aware 方法
invokeAwareMethods(beanName, bean);
} Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 执行 BeanPostProcessor before 接口
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
} try {
// 执行 init-method 方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
// 执行BeanPostProcessor after 方法
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
} return wrappedBean;
}

源码逻辑也很简单,大概就分成了4步:

  • 执行Aware接口的方法invokeAwareMethods
  • 执行BeanPostProcessor#postProcessBeforeInitialization
  • 执行初始化方法
  • 执行BeanPostProcessor#postProcessAfterInitialization

执行Aware接口的方法

点进去:

private void invokeAwareMethods(String beanName, Object bean) {
if (bean instanceof Aware) {
// 执行BeanNameAware
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
// 执行BeanClassLoaderAware
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
// 执行BeanFactoryAware
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}

这里只执行了3个接口的方法,BeanNameAwareBeanClassLoaderAwreBeanFactoryAware,在Spring容器中不止这些Aware接口,这里为什么只执行了三个Aware接口?

Spring容器BeanFactory构造时,对这三个接口进行了忽略:

public AbstractAutowireCapableBeanFactory() {
super();
ignoreDependencyInterface(BeanNameAware.class);
ignoreDependencyInterface(BeanFactoryAware.class);
ignoreDependencyInterface(BeanClassLoaderAware.class);
}

所以这里只执行了这三个Aware接口,这里忽略,实际上就是不然这些属性通过自动装配设置属性值,而是通过Spring自己的回调进行设置值。

另外我们在开始的准备BeanFactory的时候又进行了忽略Aware接口:

beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

这6个接口在哪里执行的呢?在BeanFactory准备阶段注册了一个BeanPostProcessor的实现叫ApplicationContextAwareProcessor类,这个类的before方法中就进行了调用:

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)){
return bean;
}
AccessControlContext acc = null;
if (System.getSecurityManager() != null) {
acc = this.applicationContext.getBeanFactory().getAccessControlContext();
}
if (acc != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareInterfaces(bean);
return null;
}, acc);
}
else {
// 执行Aware接口
invokeAwareInterfaces(bean);
} return bean;
} private void invokeAwareInterfaces(Object bean) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}

为什么要分开处理呢?

个人认为主要是做了个区分而已,前面三个接口输入BeanFactory范畴,而这6个接口属于ApplicationContext范畴,只是进行了归类处理而已。

执行BPP的Before方法

代码比较简单,就是循环的执行了BPPbefore接口,这里在执行的时候,实现上也执行了在Bean进行merge的时候解析的@PostConstruct注解。

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
try {
// 执行初始化方法
metadata.invokeInitMethods(bean, beanName);
}
catch (InvocationTargetException ex) {
throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
}
return bean;
}

这个方法的实现类为InitDestroyAnnotationBeanPostProcessor

执行初始化方法

执行初始化方法的时候,会分为两步,一个是执行InitializingBeanafterPropertiesSet方法,另一个是执行自定义的init-method方法

protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
// 判断当前Bean是否是实现了InitializingBean
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);
}
}
}

执行BPP的after接口

BPP的after主要是用来实现AOP的,所以这里简单介绍下,循环执行after方法的调用。

源码:

public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException { Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}

源码比较简单,就循环执行了方法的调用。

初始化就解读完了,SpringBean的创建也基本讲完,最终创建出来的Bean对象就会放入到一级缓存singletonObjects中。

Spring 源码(17)Spring Bean的创建过程(8)Bean的初始化的更多相关文章

  1. Spring源码学习笔记12——总结篇,IOC,Bean的生命周期,三大扩展点

    Spring源码学习笔记12--总结篇,IOC,Bean的生命周期,三大扩展点 参考了Spring 官网文档 https://docs.spring.io/spring-framework/docs/ ...

  2. Spring源码分析专题 —— IOC容器启动过程(上篇)

    声明 1.建议先阅读<Spring源码分析专题 -- 阅读指引> 2.强烈建议阅读过程中要参照调用过程图,每篇都有其对应的调用过程图 3.写文不易,转载请标明出处 前言 关于 IOC 容器 ...

  3. 初探Spring源码之Spring Bean的生命周期

    写在前面的话: 学无止境,写博客纯粹是一种乐趣而已,把自己理解的东西分享出去,不意味全是对的,欢迎指正! Spring 容器初始化过程做了什么? AnnotationConfigApplication ...

  4. Spring源码 17 IOC refresh方法12

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

  5. Spring源码解读Spring IOC原理

    一.什么是Ioc/DI? IoC 容器:最主要是完成了完成对象的创建和依赖的管理注入等等. 先从我们自己设计这样一个视角来考虑: 所谓控制反转,就是把原先我们代码里面需要实现的对象创建.依赖的代码,反 ...

  6. Spring源码阅读-spring启动

    web.xml web.xml中的spring容器配置 <listener> <listener-class>org.springframework.web.context.C ...

  7. Spring源码:Spring IoC容器加载过程(2)

    Spring源码版本:4.3.23.RELEASE 一.加载XML配置 通过XML配置创建Spring,创建入口是使用org.springframework.context.support.Class ...

  8. 【Spring 源码】Spring 加载资源并装配对象的过程(XmlBeanDefinitionReader)

    Spring 加载资源并装配对象过程 在Spring中对XML配置文件的解析从3.1版本开始不再推荐使用XmlBeanFactory而是使用XmlBeanDefinitionReader. Class ...

  9. Spring源码:Spring IoC容器加载过程(1)

    Spring源码版本:4.3.23.RELEASE 一.加载过程概览 Spring容器加载过程可以在org.springframework.context.support.AbstractApplic ...

  10. spring源码解析——spring源码导入eclipse

    一.前言     众所周知,spring的强大之处.几乎所有的企业级开发中,都使用了spring了.在日常的开发中,我们是否只知道spring的配置,以及简单的使用场景.对其实现的代码没有进行深入的了 ...

随机推荐

  1. BFC理解

    Block formatting context (块级格式化上下文) 页面文档由块block构成 每个block在页面上占据自己的位置 使用新的元素构建BFC overflow:hidden | a ...

  2. 【HTML5版】导出Table数据并保存为Excel

    首发我的博客 http://blog.meathill.com/tech/js/export-table-data-into-a-excel-file.html 最近接到这么个需求,要把<tab ...

  3. Content Security Policy减少劫持

    Content Security Policy减少劫持 什么是CSP? CSP是由单词 Content Security Policy 的首单词组成,是HTML5带给我们的一套全新主动防御的体系,旨在 ...

  4. 【uniapp 开发】工具类 -- MathUtil

    获取随机数 /* ** randomWord 产生任意长度随机字母数字组合 ** randomFlag 是否任意长度 min 任意长度最小位[固定位数] max 任意长度最大位 ** ** 生成6-1 ...

  5. github账号&文章选题

    ----------------------------------------------------------- https://github.com/yanpanjiao     github ...

  6. Centos搭建 Git 服务器教程

    搭建 GIT 服务器教程 下载安装 git Git 是一款免费.开源的分布式版本控制系统,用于敏捷高效地处理任何或小或大的项目. 此实验以 CentOS 7.2 x64 的系统为环境,搭建 git 服 ...

  7. Dart语言基础

    文章目录 前言:dart语言简介 一.变量 1.1.类型推导 1.2.默认值 1.3.Final 和 const修饰符 二.内建类型 2.1.数据类型 2.2.集合的相关操作 三.函数 3.1.函数的 ...

  8. Mysql集群搭建-实操

    集群安装--准备工作 官网地址 https://dev.mysql.com/doc/refman/5.7/en/mysql-cluster-install-linux-binary.html 一.环境 ...

  9. gin框架使用【2.RESTFUL API使用】

    package mainimport ( "github.com/gin-gonic/gin")func main() { router := gin.Default() rout ...

  10. GET sql注入

    靶机地址:192.168.43.156 攻击机地址:192.168.43.89 一.AppScan检查靶机sql漏洞 二.使用sqlmap利用SQL注入漏洞 1.sqlmap -u " ht ...