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

    你可能感兴趣的文章
    POP3 协议在计算机网络中的优缺点
    查看>>
    qt批量操作同类型控件
    查看>>
    Portaudio笔记-WASAPI
    查看>>
    position:fixed失效情况
    查看>>
    Qt开发笔记:QGLWidget、QOpenGLWidget详解及区别
    查看>>
    Position属性四个值:static、fixed、absolute和relative的区别和用法
    查看>>
    POSIX thread编程中关于临界区内条件变量的分析
    查看>>
    POSIX与程序可移植性
    查看>>
    posix多线程有感--自旋锁
    查看>>
    SpringBoot中集成海康威视SDK实现布防报警数据上传/交通违章图片上传并在linux上部署(附示例代码资源)
    查看>>
    POSIX标准和XSI扩展
    查看>>
    post install error,please remove node_moules before retry
    查看>>
    postcss-pxtorem 参数之selectorBlackList、exclude的用法
    查看>>
    Postek博思得标签打印机更换电脑,打印出来标签空白
    查看>>
    postfix+ dovecot搭建邮件服务器
    查看>>
    postfix在邮件服务器中的使用
    查看>>
    PostGIS 3.1.2软件安装详细教程(地图工具篇.8)
    查看>>
    PostGIS中获取所有EPSG的编码以及对应Proj4字符串
    查看>>
    SpringBoot中集成海康威视SDK实现布防报警数据上传/交通违章图片上传并在linux上部署(附示例代码资源)
    查看>>
    PostGIS在Windows上的下载与安装
    查看>>