Spring IOC源码分析(七):IOC容器的对象存储体系与bean对象的加载流程

本文主要是介绍Spring IOC源码分析(七):IOC容器的对象存储体系与bean对象的加载流程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、IOC容器的对象存储体系

1. 获取bean对象

  • spring主要通过BeanFactory接口的getBean方法来从IOC容器,即BeanFactory的实现类中获取某个bean对象实例,如下为BeanFactory的getBean方法定义:

    public interface BeanFactory {.../*** Return an instance, which may be shared or independent, of the specified bean.* <p>This method allows a Spring BeanFactory to be used as a replacement for the* Singleton or Prototype design pattern. Callers may retain references to* returned objects in the case of Singleton beans.* <p>Translates aliases back to the corresponding canonical bean name.* Will ask the parent factory if the bean cannot be found in this factory instance.* @param name the name of the bean to retrieve* @return an instance of the bean* @throws NoSuchBeanDefinitionException if there is no bean definition* with the specified name* @throws BeansException if the bean could not be obtained*/// getBean方法的其中一个版本 // 获取name对应的bean对象实例,如果是单例的则直接返回,原型的则每次创建一个新的bean对象实例Object getBean(String name) throws BeansException;...}
    
  • 在BeanFactory接口的具体实现类中,通过类型为ConcurrentHashMap的容器map来保存beanName和bean对象实例的映射。

  • 在接口设计层面,BeanFactory接口并不直接定义该映射map,只是定义从该映射map获取bean对象的方法,而是抽象了一个BeanRegistry的概念,分别在SingletonBeanRegistry定义单例bean对象的映射map和在FactoryBeanRegistrySupport定义了由FactoryBean创建的bean对象的映射map;然后BeanFactory接口的具体实现类同时实现BeanFactory接口和BeanRegistry概念的接口SingletonBeanRegistry和FactoryBeanRegistrySupport,从而实现一个完整的IOC容器,类似于使用了一种读写分离的方式来进行接口拓展。

2. 注册bean对象

  • 单例bean对象容器SingletonBeanRegistry:定义了registerSingleton注册bean对象到IOC容器中。

    public interface SingletonBeanRegistry {/*** Register the given existing object as singleton in the bean registry,* under the given bean name.* <p>The given instance is supposed to be fully initialized; the registry* will not perform any initialization callbacks (in particular, it won't* call InitializingBean's {@code afterPropertiesSet} method).* The given instance will not receive any destruction callbacks* (like DisposableBean's {@code destroy} method) either.* <p>When running within a full BeanFactory: <b>Register a bean definition* instead of an existing instance if your bean is supposed to receive* initialization and/or destruction callbacks.</b>* <p>Typically invoked during registry configuration, but can also be used* for runtime registration of singletons. As a consequence, a registry* implementation should synchronize singleton access; it will have to do* this anyway if it supports a BeanFactory's lazy initialization of singletons.* @param beanName the name of the bean* @param singletonObject the existing singleton object* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet* @see org.springframework.beans.factory.DisposableBean#destroy* @see org.springframework.beans.factory.support.BeanDefinitionRegistry#registerBeanDefinition*/void registerSingleton(String beanName, Object singletonObject);...}
    
  1. SingletonBeanRegistry接口实现类DefaultSingletonBeanRegistry

    public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {/** Cache of singleton objects: bean name to bean instance. */private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);...}
    
  2. FactoryBean创建的bean对象容器FactoryBeanRegistrySupport:继承于DefaultSingletonBeanRegistry,映射map中的bean对象实例是通过调用FactoryBean的getObject方法获取的bean对象。

    public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {/** Cache of singleton objects created by FactoryBeans: FactoryBean name to object. */private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<>(16);...}
    

3. 完整的IOC容器

  • BeanFactory的基础抽象实现类:AbstractBeanFactory,AbstractBeanFactory继承了以上的BeanFactory接口和
    SingletonBeanRegistry接口。

    public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {...}
    

二、IOC容器中bean对象的加载流程

在spring的体系结构设计当中,主要通过ApplicationContext来对外提供IOC服务,即与应用代码集成,而不是在应用代码中直接使用BeanFactory。通过ApplicationContext来初始化BeanFactory和从BeanFactory获取应用所需的bean对象。

1. 加载流程的启动:IOC容器上下文的refresh方法

  • ApplicationContext的生命周期如下:具体在AbstractApplicationContext的refresh方法定义。

    public void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {// Prepare this context for refreshing.prepareRefresh();// Tell the subclass to refresh the internal bean factory.ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();// 为beanFactory添加内部的BeanPostProcessor的bean对象等// Prepare the bean factory for use in this context.prepareBeanFactory(beanFactory);try {// Allows post-processing of the bean factory in context subclasses.postProcessBeanFactory(beanFactory);// Invoke factory processors registered as beans in the context.invokeBeanFactoryPostProcessors(beanFactory);// 从beanFactory的beanDefinitions中获取实现了BeanPostProcessor接口的beanDefinition,// 然后创建bean对象,添加到beanFactory// Register bean processors that intercept bean creation.registerBeanPostProcessors(beanFactory);// Initialize message source for this context.initMessageSource();// Initialize event multicaster for this context.initApplicationEventMulticaster();// Initialize other special beans in specific context subclasses.onRefresh();// Check for listener beans and register them.registerListeners();// Instantiate all remaining (non-lazy-init) singletons.finishBeanFactoryInitialization(beanFactory);// Last step: publish corresponding event.finishRefresh();}...}
    }
    
  • 在finishBeanFactoryInitialization方法是创建单例bean对象,在这里涉及到bean对象的整个创建流程。

  • bean对象的创建是在调用了BeanFactory的getBean方法触发的,即如果指定beanName的bean对象不存在,则开始创建该bean对象实例,如下为AbstractBeanFactory的getBean方法定义:

    public Object getBean(String name) throws BeansException {// doGetBean底层调用createBean方法创建bean对象实例return doGetBean(name, null, null, false);
    }
    

2. BeanFactory中普通bean对象的创建:不是FactoryBean创建的bean对象

  • 注意以下过程是正常bean对象的创建过程,不是由FactoryBean创建bean对象的过程。FactoryBean创建bean对象是在自身的getObject方法实现的。

  • 底层关于bean对象实例创建的核心方法为createBean:如下为AbstractAutowireCapableBeanFactory的createBean方法定义:核心过程为首先进行类加载,然后检查是否创建代理对象替代该bean对象,如果是则创建代理对象之间返回,否则进入bean对象的正常创建流程,具体在doCreateBean方法定义。

    /*** Central method of this class: creates a bean instance,* populates the bean instance, applies post-processors, etc.* @see #doCreateBean*/
    @Override
    protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)throws BeanCreationException {if (logger.isTraceEnabled()) {logger.trace("Creating instance of bean '" + beanName + "'");}RootBeanDefinition mbdToUse = mbd;// 为给定bean进行类加载// Make sure bean class is actually resolved at this point, and// clone the bean definition in case of a dynamically resolved Class// which cannot be stored in the shared merged bean definition.Class<?> resolvedClass = resolveBeanClass(mbd, beanName);if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {mbdToUse = new RootBeanDefinition(mbd);mbdToUse.setBeanClass(resolvedClass);}// Prepare method overrides.try {mbdToUse.prepareMethodOverrides();}catch (BeanDefinitionValidationException ex) {throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),beanName, "Validation of method overrides failed", ex);}try {// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.// 调用InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiation// (如果创建了bean,则还要调用BeanPostProcessor的postProcessAfterInitialization)// 调用用于生成AOP的代理对象的BeanPostProcessor,如果bean不为null,则说明产生代理对象了,可以直接返回Object bean = resolveBeforeInstantiation(beanName, mbdToUse);if (bean != null) {// 如果bean不为null ,则直接返回,这种情况通常为AOP创建了代理对象。后面的doCreateBean不再执行return bean;}}catch (Throwable ex) {throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,"BeanPostProcessor before instantiation of bean failed", ex);}try {// 正常的,非代理bean对象的创建// 包括检查是否进行了类加载(没有则进行类加载),bean对象实例创建,bean对象实例的属性赋值,init-method的调用,BeanPostProcessor的调用Object beanInstance = doCreateBean(beanName, mbdToUse, args);if (logger.isTraceEnabled()) {logger.trace("Finished creating instance of bean '" + beanName + "'");}return beanInstance;}catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {// A previously detected exception with proper bean creation context already,// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.throw ex;}catch (Throwable ex) {throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);}
    }
    
  • doCreateBean方法定义一个完整bean对象的创建,在内部完成bean对象后置处理器BeanPostProcessor的调用,初始化相关的init-methdo和InitializingBean的afterPropertiesSet的调用:

    // bean对象实例创建的核心实现方法
    protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)throws BeanCreationException {// 使用构造函数或者工厂方法来创建bean对象实例// Instantiate the bean.BeanWrapper instanceWrapper = null;if (mbd.isSingleton()) {instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);}if (instanceWrapper == null) {instanceWrapper = createBeanInstance(beanName, mbd, args);}final Object bean = instanceWrapper.getWrappedInstance();Class<?> beanType = instanceWrapper.getWrappedClass();if (beanType != NullBean.class) {mbd.resolvedTargetType = beanType;}// 修改BeanDefinition的BeanPostProcessor的执行,如合并其他BeanDefinition进来// Allow post-processors to modify the merged bean definition.synchronized (mbd.postProcessingLock) {if (!mbd.postProcessed) {try {// 调用修改BeanDefinition的BeanPostProcessor,// 即MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinitionapplyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);}catch (Throwable ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,"Post-processing of merged bean definition failed", ex);}mbd.postProcessed = true;}}...// 初始化bean对象实例,包括属性赋值,初始化方法,BeanPostProcessor的执行// Initialize the bean instance.Object exposedObject = bean;try {// 1. InstantiationAwareBeanPostProcessor执行:// 	(1). 调用InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation,//  (2). 调用InstantiationAwareBeanPostProcessor的postProcessProperties和postProcessPropertyValues// 2. bean对象的属性赋值populateBean(beanName, mbd, instanceWrapper);// 1. Aware接口的方法调用// 2. BeanPostProcess执行:调用BeanPostProcessor的postProcessBeforeInitialization// 3. 调用init-method:首先InitializingBean的afterPropertiesSet,然后应用配置的init-method// 4. BeanPostProcess执行:调用BeanPostProcessor的postProcessAfterInitializationexposedObject = initializeBean(beanName, exposedObject, mbd);}...// Register bean as disposable.try {registerDisposableBeanIfNecessary(beanName, bean, mbd);}catch (BeanDefinitionValidationException ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);}return exposedObject;
    }
    

3. FactoryBean创建的bean对象

  • FactoryBean接口在其getObject方法自定义bean对象的创建过程,而不是使用以上的createBean方法,故应用中配置的BeanPostProcessor,InitializingBean接口的方法等不会对FactoryBean创建的bean对象起作用。
  • 这样设计也保证了spring自身可以利用FactoryBean接口来创建bean对象,如内部组件,而不会受到应用代码的影响。

4. bean对象注册到IOC容器

a. 单例bean对象
  • 单例bean对象注册到IOC容器是在doGetBean方法内完成的,核心逻辑为getSingleton:调用createBean方法创建bean对象实例然后注册到单例bean对象映射map中。

    // Create bean instance.
    if (mbd.isSingleton()) {// 创建bean对象实例并注册到单例bean映射map中sharedInstance = getSingleton(beanName, () -> {try {// bean对象实例创建return createBean(beanName, mbd, args);}catch (BeansException ex) {// Explicitly remove instance from singleton cache: It might have been put there// eagerly by the creation process, to allow for circular reference resolution.// Also remove any beans that received a temporary reference to the bean.destroySingleton(beanName);throw ex;}});// 如果sharedInstance不是FactoryBean接口的实现类,则直接返回sharedInstance;// 否则调用sharedInstance的getObject方法获取实际的bean对象bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
    }
    
  • 在getSingleton方法内调用addSingleton方法将该bean对象存放到单例bean对象映射map,即singletonObjects:

    protected void addSingleton(String beanName, Object singletonObject) {synchronized (this.singletonObjects) {this.singletonObjects.put(beanName, singletonObject);this.singletonFactories.remove(beanName);this.earlySingletonObjects.remove(beanName);this.registeredSingletons.add(beanName);}
    }
    
b. FactoryBean创建的bean对象
  • FactoryBean创建的bean对象,即调用FactoryBean的getObject方法返回的bean对象,注册到IOC容器(由FactoryBean创建的bean对象的映射map,即FactoryBeanRegistrySupport的factoryBeanObjectCache),也是在doGetBean方法中实现的,具体在FactoryBeanRegistrySupport的getObjectForBeanInstance方法实现。

这篇关于Spring IOC源码分析(七):IOC容器的对象存储体系与bean对象的加载流程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/957102

相关文章

在Ubuntu上部署SpringBoot应用的操作步骤

《在Ubuntu上部署SpringBoot应用的操作步骤》随着云计算和容器化技术的普及,Linux服务器已成为部署Web应用程序的主流平台之一,Java作为一种跨平台的编程语言,具有广泛的应用场景,本... 目录一、部署准备二、安装 Java 环境1. 安装 JDK2. 验证 Java 安装三、安装 mys

Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单

《Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单》:本文主要介绍Springboot的ThreadPoolTaskScheduler线... 目录ThreadPoolTaskScheduler线程池实现15分钟不操作自动取消订单概要1,创建订单后

JAVA中整型数组、字符串数组、整型数和字符串 的创建与转换的方法

《JAVA中整型数组、字符串数组、整型数和字符串的创建与转换的方法》本文介绍了Java中字符串、字符数组和整型数组的创建方法,以及它们之间的转换方法,还详细讲解了字符串中的一些常用方法,如index... 目录一、字符串、字符数组和整型数组的创建1、字符串的创建方法1.1 通过引用字符数组来创建字符串1.2

SpringCloud集成AlloyDB的示例代码

《SpringCloud集成AlloyDB的示例代码》AlloyDB是GoogleCloud提供的一种高度可扩展、强性能的关系型数据库服务,它兼容PostgreSQL,并提供了更快的查询性能... 目录1.AlloyDBjavascript是什么?AlloyDB 的工作原理2.搭建测试环境3.代码工程1.

Java调用Python代码的几种方法小结

《Java调用Python代码的几种方法小结》Python语言有丰富的系统管理、数据处理、统计类软件包,因此从java应用中调用Python代码的需求很常见、实用,本文介绍几种方法从java调用Pyt... 目录引言Java core使用ProcessBuilder使用Java脚本引擎总结引言python

SpringBoot操作spark处理hdfs文件的操作方法

《SpringBoot操作spark处理hdfs文件的操作方法》本文介绍了如何使用SpringBoot操作Spark处理HDFS文件,包括导入依赖、配置Spark信息、编写Controller和Ser... 目录SpringBoot操作spark处理hdfs文件1、导入依赖2、配置spark信息3、cont

springboot整合 xxl-job及使用步骤

《springboot整合xxl-job及使用步骤》XXL-JOB是一个分布式任务调度平台,用于解决分布式系统中的任务调度和管理问题,文章详细介绍了XXL-JOB的架构,包括调度中心、执行器和Web... 目录一、xxl-job是什么二、使用步骤1. 下载并运行管理端代码2. 访问管理页面,确认是否启动成功

Java中的密码加密方式

《Java中的密码加密方式》文章介绍了Java中使用MD5算法对密码进行加密的方法,以及如何通过加盐和多重加密来提高密码的安全性,MD5是一种不可逆的哈希算法,适合用于存储密码,因为其输出的摘要长度固... 目录Java的密码加密方式密码加密一般的应用方式是总结Java的密码加密方式密码加密【这里采用的

Java中ArrayList的8种浅拷贝方式示例代码

《Java中ArrayList的8种浅拷贝方式示例代码》:本文主要介绍Java中ArrayList的8种浅拷贝方式的相关资料,讲解了Java中ArrayList的浅拷贝概念,并详细分享了八种实现浅... 目录引言什么是浅拷贝?ArrayList 浅拷贝的重要性方法一:使用构造函数方法二:使用 addAll(

解决mybatis-plus-boot-starter与mybatis-spring-boot-starter的错误问题

《解决mybatis-plus-boot-starter与mybatis-spring-boot-starter的错误问题》本文主要讲述了在使用MyBatis和MyBatis-Plus时遇到的绑定异常... 目录myBATis-plus-boot-starpythonter与mybatis-spring-b