博客
关于我
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/

    你可能感兴趣的文章
    python多个定时器_python单线程实现多个定时器示例
    查看>>
    python处理文本_Python - Tokenization
    查看>>
    Python处理数据方向之OpenCV
    查看>>
    python处理一亿条数据_Python数据分析实战(一)
    查看>>
    Python处理PDF神器:PyMuPDF的安装与使用
    查看>>
    Python处理Excel数据
    查看>>
    Python基础:集合与文件操作
    查看>>
    Python基础:搭建开发环境(1)
    查看>>
    PYTHON基础:如何阅读N个整数,直到#39;
    查看>>
    Python基础:11变量作用域和闭包
    查看>>
    Python基础: with模式和__enter__ 和 __exit__
    查看>>
    Python基础(7)--函数
    查看>>
    Python基础部分-while循环,格式化输出
    查看>>
    Python基础语法:顺序语句结构
    查看>>
    Python基础语法:理解代码与写代码
    查看>>
    Python基础语法:条件和分支
    查看>>
    Python基础语法:基本数据类型(数字类型和布尔类型)
    查看>>
    Python基础语法:基本数据类型(列表)
    查看>>
    Python基础语法:内置函数
    查看>>
    Python基础语法:你不得不知的几种变量类型
    查看>>