【Spring源码】 BeanFactory和FactoryBean是什么?

news2025/6/18 17:13:43

1、前言

面试官:“看过Spring源码吧,简单说说Spring中BeanFactory和FactoryBean的区别是什么?”

大神仙:“BeanFactory是bean工厂,FactoryBean是工厂bean”。

这么回答,等于面试官问你Spring是什么,你回答这个单词翻译叫春天。

2、ChitGPT的回答

首先看下C知道(ChitGPT)的回答

没错,基本上已经给出了答案。

那么接下来,我们来详细看下他们分别是什么。

3、什么是BeanFactory?

其实BeanFactory回答是bean工厂也没毛病,确实是。但是却没回答到本质。

我们知道,Spring其中一个核心功能就是IoC。Spring创建bean,使用的是经典的工厂模式,那么这一系列的bean工厂,就是IoC容器或称为对象工厂。

我们先来看下Spring源码中对于BeanFactory的注释:

/**
 * // 访问Spring bean容器的根接口
 * The root interface for accessing a Spring bean container.
 *
 * ......
 *
 * // 这个接口是由拥有许多bean定义的对象实现的,每个bean定义都由一个String名称唯一标识。
 * // 根据bean定义,工厂将返回包含对象的独立实例(原型设计模式),或者返回单个共享实例(单例设计模式的高级替代方案,在单例设计模式中,
 * // 实例在工厂范围内是单例)。将返回哪种类型的实例取决于bean工厂配置。
 * <p>This interface is implemented by objects that hold a number of bean definitions,
 * each uniquely identified by a String name. Depending on the bean definition,
 * the factory will return either an independent instance of a contained object
 * (the Prototype design pattern), or a single shared instance (a superior
 * alternative to the Singleton design pattern, in which the instance is a
 * singleton in the scope of the factory). Which type of instance will be returned
 * depends on the bean factory configuration: the API is the same. Since Spring
 * 2.0, further scopes are available depending on the concrete application
 * context (e.g. "request" and "session" scopes in a web environment).
 *
 * ......
 * 
 * // 通常,BeanFactory将加载存储在配置源(如XML文档)中的bean定义,并使用{@code org.springframework。Beans}包来配置bean。
 * // 但是,实现可以直接在Java代码中返回它根据需要创建的Java对象。对于如何存储定义没有限制:LDAP、RDBMS、XML、属性文件等等。
 * // 鼓励实现支持bean之间的引用(依赖注入)。
 * <p>Normally a BeanFactory will load bean definitions stored in a configuration
 * source (such as an XML document), and use the {@code org.springframework.beans}
 * package to configure the beans. However, an implementation could simply return
 * Java objects it creates as necessary directly in Java code. There are no
 * constraints on how the definitions could be stored: LDAP, RDBMS, XML,
 * properties file, etc. Implementations are encouraged to support references
 * amongst beans (Dependency Injection).
 *
 * ......
 * // Bean工厂实现应该尽可能支持标准的Bean生命周期接口。完整的初始化方法集及其标准顺序为:
 * <p>Bean factory implementations should support the standard bean lifecycle interfaces
 * as far as possible. The full set of initialization methods and their standard order is:
 * <ol>
 * <li>BeanNameAware's {@code setBeanName}
 * <li>BeanClassLoaderAware's {@code setBeanClassLoader}
 * <li>BeanFactoryAware's {@code setBeanFactory}
 * <li>EnvironmentAware's {@code setEnvironment}
 * <li>EmbeddedValueResolverAware's {@code setEmbeddedValueResolver}
 * <li>ResourceLoaderAware's {@code setResourceLoader}
 * (only applicable when running in an application context)
 * <li>ApplicationEventPublisherAware's {@code setApplicationEventPublisher}
 * (only applicable when running in an application context)
 * <li>MessageSourceAware's {@code setMessageSource}
 * (only applicable when running in an application context)
 * <li>ApplicationContextAware's {@code setApplicationContext}
 * (only applicable when running in an application context)
 * <li>ServletContextAware's {@code setServletContext}
 * (only applicable when running in a web application context)
 * <li>{@code postProcessBeforeInitialization} methods of BeanPostProcessors
 * <li>InitializingBean's {@code afterPropertiesSet}
 * <li>a custom {@code init-method} definition
 * <li>{@code postProcessAfterInitialization} methods of BeanPostProcessors
 * </ol>
 *
 * <p>On shutdown of a bean factory, the following lifecycle methods apply:
 * <ol>
 * <li>{@code postProcessBeforeDestruction} methods of DestructionAwareBeanPostProcessors
 * <li>DisposableBean's {@code destroy}
 * <li>a custom {@code destroy-method} definition
 * </ol>
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @author Chris Beams
 * @since 13 April 2001
 * @see BeanNameAware#setBeanName
 * @see BeanClassLoaderAware#setBeanClassLoader
 * @see BeanFactoryAware#setBeanFactory
 * @see org.springframework.context.EnvironmentAware#setEnvironment
 * @see org.springframework.context.EmbeddedValueResolverAware#setEmbeddedValueResolver
 * @see org.springframework.context.ResourceLoaderAware#setResourceLoader
 * @see org.springframework.context.ApplicationEventPublisherAware#setApplicationEventPublisher
 * @see org.springframework.context.MessageSourceAware#setMessageSource
 * @see org.springframework.context.ApplicationContextAware#setApplicationContext
 * @see org.springframework.web.context.ServletContextAware#setServletContext
 * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization
 * @see InitializingBean#afterPropertiesSet
 * @see org.springframework.beans.factory.support.RootBeanDefinition#getInitMethodName
 * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization
 * @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor#postProcessBeforeDestruction
 * @see DisposableBean#destroy
 * @see org.springframework.beans.factory.support.RootBeanDefinition#getDestroyMethodName
 */
public interface BeanFactory {
    ......
}

可以看到,BeanFactory是一个接口类,且是最顶层的一个接口类,其中定义了IoC容器的基本功能规范,用来更好的管理(或者说约束)实现类对于bean的管理,如实例化,定位,配置对应以及创建对象间依赖等。

BeanFactory有三个比较重要的接口子类:AutowireCapableBeanFactory,ListableBeanFactory,HierarchicalBeanFactory。BeanFactory有一个默认的实现类是DefaultListableBeanFactory。

在Spring中,DefaultListableBeanFactory被作为一个默认的IoC容器来使用。

来看下类图:

简化一下:

  • AutowireCapableBeanFactory:表示Bean的自动装配规则
  • ListableBeanFactory:表示Bean可列表化
  • HierarchicalBeanFactory:表示Bean有继承关系

这三个接口共同定义了Bean的集合,Bean之间的关系,以及Bean的行为。而BeanFactory是IoC容器最基本的接口类。

再来看下BeanFactory源码内容:

public interface BeanFactory {

   // 对FactoryBean的转义定义,因为如果使用bean的名字检索FactoryBean得到的对象是工厂生成的对象,
   // 如果需要得到工厂本身,需要转义
    String FACTORY_BEAN_PREFIX = "&";
    
    // 根据bean的名字,获取在IOC容器中得到bean实例
    Object getBean(String var1) throws BeansException;
    
    // 根据bean的名字和Class类型来得到bean实例,增加了类型安全验证机制。
    <T> T getBean(String var1, Class<T> var2) throws BeansException;
    Object getBean(String var1, Object... var2) throws BeansException;
    <T> T getBean(Class<T> var1) throws BeansException;
    <T> T getBean(Class<T> var1, Object... var2) throws BeansException;
    <T> ObjectProvider<T> getBeanProvider(Class<T> var1);
    <T> ObjectProvider<T> getBeanProvider(ResolvableType var1);

    // 提供对bean的检索,看看是否在IOC容器有这个名字的bean
    boolean containsBean(String var1);

    // 根据bean名字得到bean实例,并同时判断这个bean是不是单例
    boolean isSingleton(String var1) throws NoSuchBeanDefinitionException;
    boolean isPrototype(String var1) throws NoSuchBeanDefinitionException;
    boolean isTypeMatch(String var1, ResolvableType var2) throws NoSuchBeanDefinitionException;
    boolean isTypeMatch(String var1, Class<?> var2) throws NoSuchBeanDefinitionException;

    // 得到bean实例的Class类型
    @Nullable
    Class<?> getType(String var1) throws NoSuchBeanDefinitionException;

    // 得到bean的别名,如果根据别名检索,那么其原名也会被检索出来
    String[] getAliases(String var1);
}

在BeanFactory中只对IoC容器的基本行为做了定义,通过实现该接口可以实现不同的Bean检索方法。在Spring中也提供了许多IoC容器的实现,如GenericApplicationContext,ClassPathXmlApplicationContext等。

但是在Spring中,是不允许我们直接使用BeanFactory的,他给我们提供了ApplicationContext接口继承BeanFactory接口,同时进行了很多扩展:如实现国际化(实现MessageSource接口),访问资源(实现ResourcePatternResolver接口),支持应用事件(实现ApplicationEventPublisher接口)。

以下为ApplicationContext子类继承图:

4、什么是FactoryBean?

FactoryBean是一个工厂Bean。也是一个接口,该接口提供了一个工厂方法,用来返回其他Bean实例。

来看下注释:

/**
 * // 由{@link BeanFactory}中使用的对象实现的接口,这些对象本身就是单个对象的工厂。
 * // 如果一个bean实现了这个接口,那么它将被用作要公开的对象的工厂,而不是直接用作将自己公开的bean实例。
 * Interface to be implemented by objects used within a {@link BeanFactory} which
 * are themselves factories for individual objects. If a bean implements this
 * interface, it is used as a factory for an object to expose, not directly as a
 * bean instance that will be exposed itself.
 *
 * // 注意:实现该接口的bean不能作为普通bean使用。
 * // FactoryBean是以bean风格定义的,但是为bean引用公开的对象({@link #getObject()})始终是它创建的对象。
 * <p><b>NB: A bean that implements this interface cannot be used as a normal bean.</b>
 * A FactoryBean is defined in a bean style, but the object exposed for bean
 * references ({@link #getObject()}) is always the object that it creates.
 * ......
 *
 * // 该接口在框架本身中被大量使用,例如用于AOP {@link org.springframework.jndi.JndiObjectFactoryBean}。
 * // 它也可以用于定制组件;但是,这只在基础结构代码中常见。
 * <p>This interface is heavily used within the framework itself, for example for
 * the AOP {@link org.springframework.aop.framework.ProxyFactoryBean} or the
 * {@link org.springframework.jndi.JndiObjectFactoryBean}. It can be used for
 * custom components as well; however, this is only common for infrastructure code.
 * ......
 *
 * // 最后,FactoryBean对象参与了包含BeanFactory的bean创建的同步。
 * // 除了在FactoryBean本身(或类似)内进行惰性初始化之外,通常不需要内部同步。
 * <p>Finally, FactoryBean objects participate in the containing BeanFactory's
 * synchronization of bean creation. There is usually no need for internal
 * synchronization other than for purposes of lazy initialization within the
 * FactoryBean itself (or the like).
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @since 08.03.2003
 * @param <T> the bean type
 * @see org.springframework.beans.factory.BeanFactory
 * @see org.springframework.aop.framework.ProxyFactoryBean
 * @see org.springframework.jndi.JndiObjectFactoryBean
 */
public interface FactoryBean<T> {
    ......
}

但从官方给的注释上也能看出,FactoryBean其实就是个Bean,是在IoC容器的基础上给Bean的实现加上了一个简单的工厂模式和装饰模式,是一个用于生产Bean对象的工厂Bean。用户通过实现该接口,可以通过getObject()方法获取对象。

public interface FactoryBean<T> {

   // 获取容器管理的对象实例
   @Nullable
   T getObject() throws Exception;

   // 获取Bean工厂创建的对象类型
   @Nullable
   Class<?> getObjectType();

   // Bean工厂创建的对象是否单例模式,
   // 如果是,则整个容器中只有一个实例对象,每次请求都返回同一个实例对象
   default boolean isSingleton() {
      return true;
   }

}

5、小结

BeanFactory:

  • 是所有Spring中IoC容器的顶级接口,为Spring的容器定义了一套规范,并提供像getBean()方法从容器中获取Bean实例;
  • 负责生产和管理Bean的一个工厂;
  • 在产生Bean实例的同时,还提供了DI的能力;

FactoryBean:

  • 实际上就是个bean,相当于普通的Bean的实现加上了简单工厂模式和装饰模式;
  • 动态生成某一个类别的Bean实例;
  • getObject() 获取的是FactoryBean的getObject()返回的对象,而不是FactoryBean本身,如果要获取FactoryBean对象,需要在id前加一个&;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/411751.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

如何免费使用ChatGPT 4?

自从ChatGPT发布以来&#xff0c;它就取得了巨大的成功。无论是常春藤法学考试还是商学院作业&#xff0c;ChatGPT都被用于各种试验。统计数据显示&#xff0c;ChatGPT每月吸引约9600万用户。随着ChatGPT的巨大成功&#xff0c;Open AI最近推出了它的最新版本&#xff0c;名为“…

Learning to Detect Human-Object Interactions 文章解读

Learning to Detect Human-Object Interactions&#xff0c;WACV&#xff0c;2018 论文下载 code&#xff1a;http://www.umich.edu/∼ywchao/hico/ 摘要 主要研究领域&#xff1a;定义了HOI detection任务&#xff1a;在静态图像中检测人-对象交互&#xff08;HOI&#xff…

Vue路由模式为history的项目部署到Nginx

前言 对于前端工程师而言&#xff0c;多多少少会碰到按需加载的需求。 比如一个系统&#xff0c;需要用户登陆以后才能使用&#xff0c;对于传统的前后端未分离的情况&#xff0c;我们一般的处理方式是&#xff0c;当检测到用户未登录的时候&#xff0c;一般会重定向到登录页面…

JVM运行时数据区的必备知识:Java程序员不容错过

1、JVM运行时数据区概念 JVM运行时数据区是Java虚拟机在执行Java程序时所使用的内存区域。这些区域包括了以下几个部分&#xff1a; 程序计数器&#xff08;Program Counter Register&#xff09;&#xff1a;程序计数器是一块较小的内存区域&#xff0c;它可以看作是当前线程…

测试1号位的自我修养

作者&#xff1a;京东零售 吴聪 引言 目前京东实行BigBoss机制以及积木型组织&#xff0c;同时现阶段再次强调了“经营”理念&#xff0c;以上均是比较大的组织层面的纲领和引导&#xff0c;核心是为了激发大家owner意识可以更好更快为公司产出价值和贡献。落到具体执行层面&…

国内大模型领域进入乱战时代

国内大模型领域进入乱战时代 2023.4.12版权声明&#xff1a;本文为博主chszs的原创文章&#xff0c;未经博主允许不得转载。 什么是大模型 大模型&#xff0c;又称为预训练模型、基础模型等&#xff0c;是指模型参数数量很大&#xff0c;需要大量计算资源才能训练的深度学习…

RHCE-Web服务器

请给openlab搭建web网站​ 网站需求&#xff1a;​ 1.基于域名[www.openlab.com](http://www.openlab.com)可以访问网站内容为 welcome to openlab!!! 首先创建一个名为openlab的网站&#xff1a; &#xff08;1&#xff09;在www目录下创建一个openlab文件夹&#xff1a;mk…

Android UI

什么是 UI 用户界面&#xff08;User Interface&#xff0c;简称 UI&#xff0c;亦称使用者界面&#xff09;是系统和用户之间进行交互和信息交换的媒介&#xff0c;它实现信息的内部形式与人类可以接受形式之间的转换。软件设计可分为两个部分&#xff1a;编码设计与UI设计。A…

JavaScript编程实现tab选项卡切换的效果+1

之前在“圳品”信息系统使用了tab选项卡来显示信息&#xff0c;详见&#xff1a; JavaScript编程实现tab选项卡切换的效果 在tab选项卡中使用其它<div>来显示信息就出现了问题&#xff0c;乱套了&#xff0c;比如下面的这段代码&#xff1a; <!DOCTYPE html> &l…

c/c++:for循环语句,分号不可省略,表达式可以省略,猜数字游戏,跳转语句continue,break,避免写goto

c/c:for循环语句&#xff0c;分号不可省略&#xff0c;表达式可以省略&#xff0c;猜数字游戏&#xff0c;跳转语句continue&#xff0c;break&#xff0c;避免写goto 2022找工作是学历、能力和运气的超强结合体&#xff0c;遇到寒冬&#xff0c;大厂不招人&#xff0c;此时学…

树莓派 QT项目开机自启动

我自己用qt设置了一个界面&#xff0c;如何让他开机自启动呢&#xff1f; 目录 1.生成qt项目的可执行文件 2. 编写一个自启动脚本 3.重启树莓派 1.生成qt项目的可执行文件 QT项目的可执行文件就是.exe文件。首先在qt中打开&#xff0c;点击红色方框图标&#xff0c;选择Re…

vue+springboot 上传文件、图片、视频,回显到前端。

效果图 预览&#xff1a; 视频&#xff1a; 设计逻辑 数据库表 前端vue html <div class"right-pannel"><div class"data-box"><!--上传的作业--><div style"display: block" id""><div class"tit…

C++编程法则365条一天一条(359)认识各种初始化术语

文章目录Default initialization默认初始化Copy initialization拷贝初始化Aggregate initialization聚合初始化Direct initialization直接初始化list_initialization列表初始化value_initialization值初始化参考&#xff1a; https://en.cppreference.com/w/cpp/language/copy_…

【unity learn】【Ruby 2D】角色发射飞弹

前面制作了敌人的随机运动以及动画控制&#xff0c;接下来就是Ruby和Robot之间的对决了&#xff01; 世界观背景下&#xff0c;小镇上的机器人出了故障&#xff0c;致使全镇陷入了危机&#xff0c;而Ruby肩负着拯救小镇的职责&#xff0c;于是她踏上了修复机器人的旅途。 之前…

同步I/O实现Reactor和Proactor的差异

有两种高效的事件处理模式&#xff1a;Reactor模式和Proactor模式 Reactor模式 主线程只负责监听socket上是否有事件发生&#xff0c;当有事件发生时&#xff0c;主线程就将该事件放进请求队列&#xff0c;通知工作线程进程处理&#xff1b;主线程不做实质性的工作&#xff0c…

使用颜色检测有向图中的循环

给定一个有向图,检查该图是否包含循环。如果给定的图形至少包含一个循环,您的函数应返回 true,否则返回 false。 例子: 输入: n = 4, e = 6 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3 输出:是 解释: <

计网之HTTP协议和Fiddler的使用

文章目录一. HTTP概述和fidder的使用1. 什么是HTTP2. 抓包工具fidder的使用2.1 注意事项2.2 fidder的使用二. HTTP协议格式1. HTTP请求格式1.1 基本格式1.2 认识URL1.3 方法2. 请求报头关键字段3. HTTP响应格式3.1 基本格式3.2 状态码一. HTTP概述和fidder的使用 1. 什么是HTT…

VueRouter路由模式解析

VueRouter路由模式解析 前端路由的实现方式主要有两种&#xff1a;hash模式和history模式。 hash模式 在window.location对象中有一个hash字段&#xff0c;可以获取地址栏中#字符及后边的所有字符。 hash也称作锚点&#xff0c;本身是用来做页面定位的&#xff0c;可以使对…

BGP联邦实验

实验目的&#xff1a; 实验拓扑&#xff1a; IP地址规划&#xff1a; AS2内部&#xff1a; 172.16.0.0/16 172.16.0.0/24---P2P网络 172.16.1.0/24----MA网络 172.16.1.0/29 172.16.1.8/29 172.16.1.16/29 172.16.1.24/29 172.16.1.32/29 172.16.1.40/29 172.16.2.0/24--…

Golang每日一练(leetDay0032) 二叉树专题(1)

目录 94. 二叉树的中序遍历 Binary Tree Inorder Traversal &#x1f31f; 95. 不同的二叉搜索树 II Unique Binary Search Trees II &#x1f31f;&#x1f31f; 96. 不同的二叉搜索树 Unique Binary Search Trees &#x1f31f;&#x1f31f; &#x1f31f; 每日一练刷…