博客
关于我
Spring源码系列(十一)Spring创建Bean的过程(一)
阅读量:487 次
发布时间:2019-03-07

本文共 4470 字,大约阅读时间需要 14 分钟。

Spring Bean创建过程简述

1. Bean的创建前提

从今天开始,我将开始介绍Spring Bean的创建过程,这是Spring框架中非常重要的一部分。创建Bean的过程涉及到Spring的内置BeanPostProcessor的执行顺序,这些BeanPostProcessor对Bean的整个生命周期起到关键作用,从初始化到实例化再到销毁等环节都有参与。因此,我计划详细讲解这些内置BeanPostProcessor的作用及执行时机。

2. Spring的内置BeanPostProcessor有哪些?在哪录入的?

为了支持AOP(面向切面编程),我开启了一个AOP的支持,主要通过@EnableAspectJAutoProxy注解来实现。这个注解会自动添加一个BeanPostProcessor,用来处理生成代理类的相关逻辑。通过查看代码,可以看到有7个BeanPostProcessor被添加到Spring的容器中。

通过代码分析,可以看出,这些BeanPostProcessor主要有以下几种类型:

  • ApplicationContextAwareProcessor:用于处理ApplicationContext相关的逻辑。
  • ApplicationListenerDetector:用于检测ApplicationListener。
  • ImportAwareBeanPostProcessor:用于处理导入相关的逻辑。
  • AutowiredAnnotationBeanPostProcessor:用于处理注入相关的逻辑。
  • CommonAnnotationBeanPostProcessor:用于处理JSR-250注解。
  • PersistenceAnnotationBeanPostProcessor:用于处理JPA注解。
  • AnnotationAwareAspectJAutoProxyCreator:用于处理AOP的代理创建。
  • 这些BeanPostProcessor主要是在哪些地方添加的呢?

  • ApplicationContextAwareProcessorApplicationListenerDetector:在prepareBeanFactory方法中添加。
  • ImportAwareBeanPostProcessor:在postProcessBeanFactory方法中添加。
  • AnnotationConfigApplicationContext:在构造函数中通过registerBeanDefinitions方法添加。
  • 3. Spring创建Bean的过程

    Spring创建Bean的过程非常复杂,涉及多个步骤和BeanPostProcessor的参与。为了简化理解,我会从createBean方法入手,讲述Bean的创建过程。

    3.1 createBean方法概述

    createBean方法的主要职责是创建Bean实例。以下是方法的关键部分:

    protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {    // 判断是否已经创建过该Bean    if (logger.isTraceEnabled()) {        logger.trace("Creating instance of bean '" + beanName + "'");    }    // 获取Bean的类    Class
    resolvedClass = resolveBeanClass(mbd, beanName); // 如果BeanClass为空且BeanClassName不为空,使用BeanClass if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { mbd = new RootBeanDefinition(mbd); mbd.setBeanClass(resolvedClass); } // 准备方法注入逻辑 try { mbd.prepareMethodOverrides(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName, "Validation of method overrides failed", ex); } // 调用BeanPostProcessor的beforeInstantiation方法 try { Object bean = resolveBeforeInstantiation(beanName, mbd); if (bean != null) { return bean; } } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex); } // 创建Bean实例 try { Object beanInstance = doCreateBean(beanName, mbd, args); if (logger.isTraceEnabled()) { logger.trace("Finished creating instance of bean '" + beanName + "'"); } return beanInstance; } catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) { throw ex; } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex); }}

    3.2 resolveBeforeInstantiation方法

    resolveBeforeInstantiation方法的主要作用是调用BeanPostProcessor的beforeInstantiation方法,以便在Bean实例化之前进行处理。

    protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {    Object bean = null;    if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {            Class
    targetType = determineTargetType(beanName, mbd); if (targetType != null) { bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName); if (bean != null) { bean = applyBeanPostProcessorsAfterInitialization(bean, beanName); } } } mbd.beforeInstantiationResolved = (bean != null); } return bean;}

    3.3 BeanPostProcessor的执行顺序

    applyBeanPostProcessorsBeforeInstantiation方法中,所有实现InstantiationAwareBeanPostProcessor接口的BeanPostProcessor都会被调用。这些BeanPostProcessor包括:

  • ImportAwareBeanPostProcessor:处理导入逻辑。
  • AutowiredAnnotationBeanPostProcessor:处理注入逻辑。
  • AnnotationAwareAspectJAutoProxyCreator:处理AOP代理逻辑。
  • CommonAnnotationBeanPostProcessor:处理JSR-250注解。
  • 每个BeanPostProcessor都会执行自己的postProcessBeforeInstantiation方法。例如:

    • AnnotationAwareAspectJAutoProxyCreator会处理AOP代理相关逻辑。
    • AutowiredAnnotationBeanPostProcessor会处理注入相关逻辑。

    通过上述逻辑,可以看出,Spring在Bean实例化之前会依次调用这些BeanPostProcessor的beforeInstantiation方法,确保Bean的创建过程符合预期。

    4. 写在最后

    整个Spring创建Bean的过程非常复杂,涉及多个步骤和BeanPostProcessor的协作。今天的这篇博客只是一个初步的介绍,详细讲解每个BeanPostProcessor的具体作用和执行逻辑还需要后续的博客来展开。希望今天的内容能为大家提供一个基本的理解,帮助你更好地理解Spring的Bean创建过程。

    转载地址:http://cezcz.baihongyu.com/

    你可能感兴趣的文章
    Openwrt LuCI模块练习详细步骤
    查看>>
    OpenWrt固件编译刷机完全总结
    查看>>
    Open××× for Linux搭建之二
    查看>>
    Open×××有线网络时使用正常,无线网络时使用报错的解决方案
    查看>>
    Operation not supported on read-only collection 的解决方法 - [Windows Phone开发技巧系列1]
    查看>>
    Operations Manager 2007 R2系列之仪表板(多)视图
    查看>>
    operator new 与 operator delete
    查看>>
    operator() error
    查看>>
    OPPO K3在哪里打开USB调试模式的完美方法
    查看>>
    Optional类:避免NullPointerException
    查看>>
    ORA-00932: inconsistent datatypes: expected - got NCLOB【ORA-00932: 数据类型不一致: 应为 -, 但却获得 NCLOB 】【解决办法】
    查看>>
    ORA-00942 表或视图不存在
    查看>>
    ORA-01795: 列表中的最大表达式数为 1000
    查看>>
    ORA-06575: 程序包或函数 NO_VM_DROP_PROC 处于无效状态
    查看>>
    ORA-08102的错误
    查看>>
    ORA-12505, TNS:listener does not currently know of SID given in connect descriptor异常
    查看>>
    ora-12541:tns:no listener
    查看>>
    【docker知识】联合文件系统(unionFS)原理
    查看>>
    ORACEL学习--理解over()函数
    查看>>
    oracle 10g crs命令,Oracle 10g CRS安装问题解决一例
    查看>>