当前位置: 首页 > news >正文

Difference between BeanFactory and FactoryBean in Spring

Table of Contents

1. BeanFactory
2. FactoryBean2.1. Analysis2.2. Practice
3. SummaryBeanFactory is one of the core interfaces of the Spring Framework for managing and obtaining instances of beans in an application. It is an implementation of the Factory pattern and is responsible for creating, configuring, and managing Bean objects.BeanFactory is the foundation of the Spring IoC container, which reads Bean definitions from configuration metadata (e.g., an XML file) and instantiates and delivers those Beans when needed.
FactoryBean is a special bean that is a factory object used to create and manage instances of other beans; the FactoryBean interface defines a way to create beans that allows developers to do more customization in the bean creation process. By implementing the FactoryBean interface, developers can create complex instances of a bean or perform some additional logical processing before the bean is instantiated.

The difference is that a BeanFactory is the core interface of the Spring Framework that manages and provides instances of a bean, while a FactoryBean is a special bean that creates and manages instances of other beans.FactoryBean provides more customization during the creation of a bean, allowing for additional logical processing.

1. BeanFactory
BeanFactory See the name to know that this is a bean factory, Spring IoC container to help us complete the creation of beans, management and other operations, so these operations are inseparable from the BeanFactory.

public interface BeanFactory {/*This variable actually says that if the current bean is not a normal bean like User or Book, but a FactoryBean, then add an & prefix to the name of the bean, which I will demonstrate in the second subsection.*/String FACTORY_BEAN_PREFIX = "&";
/*This method looks up the bean by its name, type, etc. It can be used to retrieve the bean from the factory;*/Object getBean(String name) throws BeansException;<T> T getBean(String name, Class<T> requiredType) throws BeansException;Object getBean(String name, Object... args) throws BeansException;<T> T getBean(Class<T> requiredType) throws BeansException;<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
/* this method can get an ObjectProvider, ObjectProvider is an interface in the Spring framework, used to get the instance of the bean object. It provides a way to delay loading a bean and dynamically obtain a bean instance when needed (lazy loading).*/<T> ObjectProvider<T> getBeanProvider(Class<T> requiredType);<T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType);
//determine whether a bean is contained.boolean containsBean(String name);
//determines if a Bean is singleton.boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
//determine if a Bean is a multiple instance.boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
//Determines if a Bean is of a given type.boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException;@NullableClass<?> getType(String name) throws NoSuchBeanDefinitionException; //Get the type of a Bean@NullableClass<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException; //Get the aliases of a Bean.String[] getAliases(String name);
}

Many people are just starting to get in touch with Spring, will use an object ClassPathXmlApplicationContext, which is actually a subclass of BeanFactory. Let’s look at the inheritance diagram of BeanFactory:
image
Inheritance class is more as following:

  • ClassPathXmlApplicationContext: this is the Spring container startup, from the current class path to load the XML configuration file, the parameter is the classpath XML file path.
  • FileSystemXmlApplicationContext: this is the Spring container startup, from the file system to load the XML configuration file, the parameter is an absolute path.
  • AnnotationConfigApplicationContext: this is if we use Java code to do the Spring container configuration, through the configuration class to load the Java configuration class.
  • DefaultListableBeanFactory: this default implementation of the ListableBeanFactory and BeanDefinitionRegistry interface, is a more mature BeanFactory.

2.BeanFactory.
2.1. Analysis
FactoryBean actually many people may have seen, just may not go to summarize the generalization. Let me give you some examples.
In SpringBoot project using mybatis, if we want to configure MyBatis to the project, generally need to configure the following Bean:

<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="typeAliasesPackage" value="org.javaboy.shirodemo.model"/><property name="mapperLocations"><list><value>classpath*:org/javaboy/shirodemo/mapper/*.xml</value></list></property>
</bean>

When we configure Shiro, we typically configure the following beans:

<bean class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" id="shiroFilter"><property name="securityManager" ref="securityManager"/><property name="loginUrl" value="/login"/><property name="successUrl" value="/index"/><property name="unauthorizedUrl" value="/unauthorizedUrl"/><property name="filterChainDefinitions"><value>/index=anon/doLogin=anon/hello=user/**=authc</value></property>
</bean>

If there is a date string in the form parameters submitted by the front-end and the controller method uses a Date object to accept it, then SpringMVC can’t handle this date by default and you need to configure a date converter, generally we add the following bean in the Spring container.

<bean class="org.springframework.format.support.FormattingConversionServiceFactoryBean" id="conversionService"><property name="converters"><set><ref bean="myDateConverter"/></set></property>
</bean>
<mvc:annotation-driven conversion-service="conversionService"/>

Looking at the above three beans, there is a common feature, that is, the name of the bean is xxxFactoryBean

Why use xxxFactoryBean instead of injecting the required bean directly into the Spring container? Let’s take MyBatis as an example:
If you have manually configured MyBatis you will know that MyBatis has two important classes, one is SqlSessionFactory, and the other is SqlSession, through the SqlSessionFactory can get a SqlSession.

public class SqlSessionFactoryUtils {private static SqlSessionFactory SQLSESSIONFACTORY = null;public static SqlSessionFactory getInstance() {if (SQLSESSIONFACTORY == null) {try {SQLSESSIONFACTORY = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));} catch (IOException e) {e.printStackTrace();}}return SQLSESSIONFACTORY;}
}
public class Main {public static void main(String[] args) {SqlSessionFactory factory = SqlSessionFactoryUtils.getInstance();SqlSession sqlSession = factory.openSession();List<User> list = sqlSession.selectList("org.javaboy.mybatis01.mapper.UserMapper.getAllUser");for (User user : list) {System.out.println("user = " + user);}sqlSession.close();}
}

As you can see, neither SqlSessionFactory nor SqlSession is constructed with the new keyword. In fact, both are interfaces, so it’s obviously not possible to use the new keyword directly. The former through the builder pattern to configure various properties, and finally generate an instance of SqlSessionFactory, the latter by the SqlSessionFactory to generate. The final object is an instance of a subclass of both interfaces.
So, since SqlSessionFactory and SqlSession can’t be configured directly in the Spring container, you can configure such beans through xxxFactoryBean.
Let’s take a look at the SqlSessionFactoryBean class. The source code is very long, so I’ve picked out the important ones:

public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {private SqlSessionFactory sqlSessionFactory;@Override
/*he object returned by this method is the real object to be registered to the Spring container, in this method, we can be configured in a variety of ways on the bean*/public SqlSessionFactory getObject() throws Exception {if (this.sqlSessionFactory == null) {afterPropertiesSet();}return this.sqlSessionFactory;}@Override
/*This method returns the type of the object that is registered with the Spring container.*/public Class<? extends SqlSessionFactory> getObjectType() {return this.sqlSessionFactory == null ? SqlSessionFactory.class : this.sqlSessionFactory.getClass();}@Override
/*This method is used to return whether the bean registered to the Spring container is singleton*/public boolean isSingleton() {return true;}
}

SqlSessionFactoryBean needs to implement the FactoryBean interface and specify the generic type SqlSessionFactory when implementing the interface, which means that the final bean produced by the SqlSessionFactoryBean will be SqlSessionFactory. After implementing the FactoryBean interface, you need to implement the three methods in the interface:This is the characteristic of FactoryBean, because the initialization of a bean is too complicated, then you can use FactoryBean to help register to the Spring container.

2.2. Practice
the following class:
public class Author {

private String name;
private Integer age;private Author() {
}public static Author init(String name, Integer age) {Author author = new Author();author.setAge(age);author.setName(name);return author;
}

}
The feature of this class is that the constructor method is private and you can’t create an instance of it directly using the new keyword. Now I want to register the objects of this class with the Spring container, so I can provide an AuthorFactoryBean.

public class AuthorFactoryBean implements FactoryBean<Author> {@Overridepublic Author getObject() throws Exception {return Author.init("javaboy", 99);}@Overridepublic Class<?> getObjectType() {return Author.class;}@Overridepublic boolean isSingleton() {return true;}
}

Then you can configure the AuthorFactoryBean in the Spring container.

<bean class="org.javaboy.bean.AuthorFactoryBean" id="author"/>

Next, we can get the Author object from the container, but note that the name author gets the Author object, not the AuthorFactoryBean object, and if you want to get the AuthorFactoryBean object, you have to get it by the name &author (recall what was said in the first subsection).

public class Main {public static void main(String[] args) {ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");Object author = ctx.getBean("author");Object authorFactoryBean = ctx.getBean("&author");System.out.println("author.getClass() = " + author.getClass());System.out.println("authorFactoryBean.getClass() = " + authorFactoryBean.getClass());}
}

The results of the run are as follows.

author.getClass()=class org.javaoy.bean.Author
authorFactoryBean.getClass()=class org.javaboy.bean.AuthorFactoryBean

3. Summary
The difference is that a BeanFactory is the core interface of the Spring Framework that manages and provides instances of a bean, while a FactoryBean is a special bean that creates and manages instances of other beans.FactoryBean provides more customization during the creation of a bean, allowing for additional logical processing.
Reference: https://mp.weixin.qq.com/s/r3rnVhU8vr58Cw__UWOVLA

http://www.jsqmd.com/news/382431/

相关文章:

  • [特殊字符] AI闪应用爆火!超算互联网,免费托管你的创意!
  • 2026年目前评价高的AI搜索企业口碑推荐榜,抖音头条信息流广告/视频矩阵/广告代运营,AI搜索企业推荐 - 品牌推荐师
  • Flutter 项目结构为什么“看起来干净,后期却很难改“?
  • 在职护士怎么备考2026主管护师?三轮备考法+三个提分技巧,一次上岸! - 医考机构品牌测评专家
  • 2026主管护师备考:一位过来人的3个“巧学”备考方法,在职护士这样学更省力 - 医考机构品牌测评专家
  • 2026年鼠标微动开关供应商优选指南,快收藏,鼠标微动开关/电动推杆微动开关,鼠标微动开关制造企业怎么选购 - 品牌推荐师
  • 不再丢失资产!机房U位管理系统核心功能解析,让管理更轻松
  • 2026口碑推荐:水下清淤机器人实力厂家精选排行,目前水下清淤机器人直销厂家优质品牌选购指南 - 品牌推荐师
  • 西方情人节:从暴力祭祀到为爱殉道
  • 第1章 程序点滴-1.4 开放性思维(1)
  • 2026年市面上专业的投影机工厂排行榜,户外投影机出租/雾幕投影机/水幕投影机出租,投影机生产厂家哪家权威 - 品牌推荐师
  • 洛谷P1073 [NOIP 2009 提高组] 最优贸易 题解
  • 深入解析:大数据分析入门:Hadoop 生态系统与 Python 结合的分布式数据处理实践
  • python微信小程序的校园物品租赁与二手交易系统
  • USB基础知识学习笔记
  • 第1章 程序点滴-1.4 开放性思维(2)
  • 豆包能做广告吗?doubaoAD:专注于豆包搜索优化推广(GEO)的科技服务商 - 品牌2025
  • python微信小程序的班级课堂考勤学生签到系统
  • PADS Layout里的条件筛选在Router里在哪找
  • 笔记(动态规划(引入)1)
  • python微信小程序的师范生实习管理系统
  • 每日一题(P1563 [NOIP 2016 提高组] 玩具谜题)(第1天)
  • python微信小程序的日常活动记录系统
  • Linux iptables核心能力概述
  • Spring SpringMVC SpringBoot SpringCloud SpringAI 分别是做什么的
  • Arbess项目实战 - 基于GitLab搭建Node.js方案自动化流水线
  • 【2025最新】基于SpringBoot+Vue的交通管理在线服务系统管理系统源码+MyBatis+MySQL
  • python微信小程序的家乡扶贫助农系统设计与实现
  • 前后端分离火锅店管理系统系统|SpringBoot+Vue+MyBatis+MySQL完整源码+部署教程
  • 当 AI 走上春晚:一场“全民智能时代”背后的工程真相