Spring源码-浅识BeanFactory

这篇具有很好参考价值的文章主要介绍了Spring源码-浅识BeanFactory。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Spring是如何启动的

在SpringBoot出现之前,我们使用Spring需要以配置文件的方式进行启动.如果使用XML文件配置.则通过XmlWebApplicationContext.java进行启动.常应用在Web项目的开发中.
以此为例,通过阅读源码发现和XmlWebApplicationContext.java"平级"的类如下所示
ApplicationContext.png
由此我们可以知道ApplicationContext遵循ApplicationContext.java的定义.如下所示其父依赖结构
image.png
此时我们可以看到最顶层的接口BeanFactory.java

揭开BeanFactory的面纱

BeanFactory本质是一个赤裸裸的接口

忽略掉繁杂的定义,BeanFactory.java 本质上就是一个接口——其中定义了一些方法。如下图示——并没有太多复杂的东西。
image.png

从官方注释提炼重要信息

  • The root interface for accessing a Spring bean container

为什么这样讲——我们需要获得一个bean的话,必须通过getBean方法,而getBean方法在该接口中定义。而其他的关于Bean的原生操作方法,如getType、containsBean、isSingleTon等接口均在BeanFactory.java中定义。

  • This interface is implemented by objects that hold a number of bean definitions,each uniquely identified by a String name.

这句话解释了BeanFactory接口由哪些对象使用。由包含多个bean定义的对象使用。每一个bean对象拥有一个String类型的name来作为唯一标识,不可重复。

层层依赖的接口关系

下图是实现了BeanFactory依赖关系

image.png
由上图可知,在Spring体系中关于Bean的定义操作都在上图中有体现。下面搞清楚各个接口的作用

ConfigurableBeanFactory
Configuration interface to be implemented by most bean factories. 
Provides facilities to configure a bean factory, 
in addition to the bean factory client methods in the {@link org.springframework.beans.factory.BeanFactory} interface
AutowireCapableBeanFactory

官方注释

Extension of the {@link org.springframework.beans.factory.BeanFactory} interface to be implemented by bean factories that are capable of autowiring, provided that they want to expose this functionality for existing bean instances

方法实现

image.png


该接口是支持自动装配的BeanFactory.是对BeanFactory接口的扩展。被支持自动装配的 bean factories 所实现。通俗点讲:通过该接口创建的Bean将会被公开暴露使用。

  • 主要定义的方法及其作用
createBean
Fully create a new bean instance of the given class
<p>Performs full initialization of the bean, including all applicable {@link BeanPostProcessor BeanPostProcessors}.
Note: This is intended for creating a fresh instance, populating annotated fields and methods as well as applying all standard bean initialization callbacks.
It does <i>not</> imply traditional by-name or by-type autowiring of properties;
use {@link #createBean(Class, int, boolean)} for those purposes.

通过给定的class,完全地创建一个新的Bean实例
执行bean的完全初始化,包含了所有可用的 BeanPostProcessors
注意:这是为了创建一个新的bean实例 
autowireBean

依赖注入的体现

	/**
	 * Populate the given bean instance through applying after-instantiation callbacks
	 * and bean property post-processing (e.g. for annotation-driven injection).
	 * <p>Note: This is essentially intended for (re-)populating annotated fields and
	 * methods, either for new instances or for deserialized instances. It does
	 * <i>not</i> imply traditional by-name or by-type autowiring of properties;
	 * use {@link #autowireBeanProperties} for those purposes.
	 * @param existingBean the existing bean instance
	 * @throws BeansException if wiring failed
	 */

应用于Bean实例化之后回调和Bean属性后置处理器来给指定的Bean进行注入
configureBean
	/**
	 * Configure the given raw bean: autowiring bean properties, applying
	 * bean property values, applying factory callbacks such as {@code setBeanName}
	 * and {@code setBeanFactory}, and also applying all bean post processors
	 * (including ones which might wrap the given raw bean).
	 * <p>This is effectively a superset of what {@link #initializeBean} provides,
	 * fully applying the configuration specified by the corresponding bean definition.
	 * <b>Note: This method requires a bean definition for the given name!</b>
	 * @param existingBean the existing bean instance
	 * @param beanName the name of the bean, to be passed to it if necessary
	 * (a bean definition of that name has to be available)
	 * @return the bean instance to use, either the original or a wrapped one
	 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
	 * if there is no bean definition with the given name
	 * @throws BeansException if the initialization failed
	 * @see #initializeBean
	 */

对原始Bean进行相关配置,自动装配bean的属性

该方法具体实现的功能

	@Override
	public Object configureBean(Object existingBean, String beanName) throws BeansException {
		// 首先把bean标记为已创建
		markBeanAsCreated(beanName);
		// 拿到 beanDefinition
		BeanDefinition mbd = getMergedBeanDefinition(beanName);
		RootBeanDefinition bd = null;
		if (mbd instanceof RootBeanDefinition) {
			RootBeanDefinition rbd = (RootBeanDefinition) mbd;
			bd = (rbd.isPrototype() ? rbd : rbd.cloneBeanDefinition());
		}
		if (bd == null) {
			bd = new RootBeanDefinition(mbd);
		}
		if (!bd.isPrototype()) {
			bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
			bd.allowCaching = ClassUtils.isCacheSafe(ClassUtils.getUserClass(existingBean), getBeanClassLoader());
		}
		// bean 的包装器  设置了属性  defaultEditorsActive=true
		BeanWrapper bw = new BeanWrapperImpl(existingBean);
		// 初始化wrapper,读取bean标签的配置信息
		initBeanWrapper(bw);
		// 注入bean属性
		populateBean(beanName, bd, bw);
		// For the nullability warning, see the elaboration in AbstractBeanFactory.doGetBean;
		// in short: This is never going to be null unless user-declared code enforces null.
		// 真正去初始化bean
		return initializeBean(beanName, existingBean, bd);
	}

    //  双重检查锁,单例模式的运用.也体现了_spring创建bean是以多线程的方式创建的
	protected void markBeanAsCreated(String beanName) {
		if (!this.alreadyCreated.contains(beanName)) {
			synchronized (this.mergedBeanDefinitions) {
				if (!this.alreadyCreated.contains(beanName)) {
					// Let the bean definition get re-merged now that we're actually creating
					// the bean... just in case some of its metadata changed in the meantime.
                    //  从待创建状态进入标记创建状态
					clearMergedBeanDefinition(beanName);
					this.alreadyCreated.add(beanName);
				}
			}
		}
	}
autowire

Instantiate a new bean instance of the given class with the specified autowire strategy
实例化一个新的Bean实例通过给定的类使用指定的自动装配策略

autowireBeanProperties

Autowire the bean properties of the given bean instance by name or type
通过name or type来给指定的类自动装配bean属性

applyBeanPropertyValues

Apply the property values of the bean definition with the given name to the given bean instance
应用属性值到bean definition

initializeBean
Initialize the given raw bean, applying factory callbacks such as {@code setBeanName} and {@code setBeanFactory}, 
also applying all bean post processors (including ones which might wrap the given raw bean)

初始化一个原始的bean.  
应用于以下四种地方
	setBeanName
  setBeanFactory
  bean post processors
  wrap the given ram bean
applyBeanPostProcessorsBeforeInitialization

Apply {@link BeanPostProcessor BeanPostProcessors} to the given existing bean instance, invoking their {@code postProcessBeforeInitialization} methods.
The returned bean instance may be a wrapper around the original.

applyBeanPostProcessorsAfterInitialization
Apply {@link BeanPostProcessor BeanPostProcessors} to the given existing bean instance, invoking their {@code postProcessAfterInitialization} methods.
The returned bean instance may be a wrapper around the original
HierarchicaBeanFactory

提供获取Bean Factory的 parent Bean Factory接口

Sub-interface implemented by bean factories that can be part of a hierarchy

如果一个bean是层次结构中的一部分,可以实现该接口
ListableBeanFactory
Extension of the {@link BeanFactory} interface to be implemented by bean factories that can enumerate all their bean instances, 
rather than attempting bean lookup by name one by one as requested by clients. 
BeanFactory implementations that preload all their bean definitions (such as XML-based factories) may implement this interface.
image.png

主要定义了BeanDefinition相关操作文章来源地址https://www.toymoban.com/news/detail-438480.html

ConfigurableListableBeanFactory
* Configuration interface to be implemented by most listable bean factories.
* In addition to {@link ConfigurableBeanFactory}, it provides facilities to
* analyze and modify bean definitions, and to pre-instantiate singletons.
ApplicationContext
Central interface to provide configuration for an application.
This is read-only while the application is running, but may be
reloaded if the implementation supports this.
ConfigurableApplicationContext
SPI interface to be implemented by most if not all application contexts.
Provides facilities to configure an application context in addition
to the application context client methods in the
{@link org.springframework.context.ApplicationContext} interface.
WebApplicationContext
Interface to provide configuration for a web application. This is read-only while
the application is running, but may be reloaded if the implementation supports this.
ConfigurableWebApplicationContext
Interface to be implemented by configurable web application contexts.
Supported by {@link ContextLoader} and
{@link org.springframework.web.servlet.FrameworkServlet}.

到了这里,关于Spring源码-浅识BeanFactory的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • spring的BeanFactory和applicationContext有什么区别?

            ApplicationContext是一次性立刻加载,比较 消耗资源 但是后续读取非常快,会将spring中所有的bean进行初始化,全部实例化到spring中!!属于 饿汉模式加载 。         Beanfactory是一个用来管理bean对象的工厂,加载bean的时候不会立刻一次性加载,使用的是 惰性加载 ,只有执

    2023年04月21日
    浏览(23)
  • FactoryBean和BeanFactory:Spring IOC容器的两个重要角色简介

    目录 一、简介 二、BeanFactory 三、FactoryBean 四、区别 五、使用场景 总结 在Spring框架中,IOC(Inversion of Control)容器是一个核心组件,它负责管理和配置Java对象及其依赖关系,实现了控制反转(Inversion of Control)和依赖注入(Dependency Injection)两个核心概念。 控制反转是一种设

    2024年02月11日
    浏览(25)
  • Mr. Cappuccino的第60杯咖啡——Spring之BeanFactory和ApplicationContext

    概述 BeanFactory,以Factory结尾,表示它是一个工厂类(接口), 它是负责生产和管理bean的一个工厂。在Spring中,BeanFactory是IOC容器的核心接口,它的职责包括:实例化、定位、配置应用程序中的对象及建立这些对象间的依赖; BeanFactory只是个接口,并不是IOC容器的具体实现,但是

    2024年02月13日
    浏览(27)
  • Spring Boot启动源码分析

    版本:spring-boot-starter-parent版本为2.3.0 Spring Boot项目的启动入口是一个main方法,因此我们从该方法入手即可 跟踪run方法 这里分两步debug: new SpringApplication( primarySources ) 执行run()方法 deduceFromClasspath推断应用程序类型 该方法根据是否存在指定路径的类来推断应用程序类型。有

    2024年02月07日
    浏览(37)
  • 11.spring boot 启动源码(一)

    spring boot 版本 2.6.13 spring boot 启动源码(一) 涉及 SpringApplication 中静态与实例方法 run 方法源码解析、配置文件和 Actuator

    2024年01月19日
    浏览(29)
  • 【Spring学习】走进spring,spring的创建和使用,spring获取Bean的几种常见方式, ApplicationContext 和 BeanFactory的区别(重点面试)

    前言: 大家好,我是 良辰丫 ,我们在上一篇文章不是简单介绍了SpringBoot嘛,为什么不学习SpringBoot,而是要开始Spring呢?Spring是SpringBoot的前身,我们先学习以前的稍微复杂的框架,才能更好的学习SpringBoot.💌💌💌 🧑个人主页:良辰针不戳 📖所属专栏:javaEE进阶篇之框架学习 🍎励志

    2024年02月08日
    浏览(32)
  • 【spring源码系列-04】注解方式启动spring时refresh的前置工作

    Spring源码系列整体栏目 内容 链接地址 【一】spring源码整体概述 https://blog.csdn.net/zhenghuishengq/article/details/130940885 【二】通过refresh方法剖析IOC的整体流程 https://blog.csdn.net/zhenghuishengq/article/details/131003428 【三】xml配置文件启动spring时refresh的前置工作 https://blog.csdn.net/zhenghuishen

    2024年02月08日
    浏览(28)
  • Spring retry(二)- 源码解析-启动装配篇 @EnableRetry

    上一篇文章,我们快速介绍了下spring-retry的使用技巧,本篇我们将会剖析源码去学习 英文翻译我就不再解释了,上面说的很清楚;这里重点提一下@Import(RetryConfiguration.class)这个注解,表明了@EnableRetry注解的启动配置类是RetryConfiguration, 通过@Import注解来注入对应的配置类,这

    2024年02月10日
    浏览(24)
  • 理解SpringIOC和DI第一课(Spring的特点),IOC对应五大注解,ApplicationContext vs BeanFactory

    对象这个词在Spring范围内,称为bean Spring两大核心思想 1.IOC     (IOC是控制反转,意思是 控制权反转-控制权(正常是谁用这个对象,谁去创建,)-控制对象的控制权,反转的意思是创建对象的控制权,交给了Spring) 优点:解耦合 高内聚:一个模块内部的关系 低耦合:各个模

    2024年02月04日
    浏览(33)
  • Spring之BeanFactory与ApplicationContext区别、实例化Bean的三种⽅式、延迟加载(lazy-Init )

    BeanFactory是Spring框架中IoC容器的顶层接⼝,它只是⽤来定义⼀些基础功能,定义⼀些基础规范,⽽ApplicationContext是它的⼀个⼦接⼝,所以ApplicationContext是具备BeanFactory提供的全部功能的。 通常,我们称BeanFactory为SpringIOC的基础容器, ApplicationContext是容器的⾼级接⼝,⽐BeanFactory要拥

    2024年02月11日
    浏览(29)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包