Spring中BeanFactory与ApplicationContext的区别

本文详细介绍了Spring框架中的两种主要容器BeanFactory与ApplicationContext的功能差异。ApplicationContext不仅具备BeanFactory的功能,还提供了国际化支持、资源访问、事件传递等高级特性,并能够自动检测BeanPostProcessor。此外,还列举了多种创建ApplicationContext的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

BeanFactory:Bean工厂接口,是访问Spring Bean容器的根接口,基本Bean视图客户端。从其名称上即可看出其功能,即实现Spring Bean容器的读取。

ApplicationContext:一个应用配置的中心接口,提供以下功能:

1.Bean factory methods for accessing application components,Inherited from {@link org.springframework.beans.factory.ListableBeanFactory}.(Bean工厂访问应用组件方法)

2.The ability to load file resources in a generic fashion.Inherited from the {@link org.springframework.core.io.ResourceLoader} interface.(以通用方式加载文件资源的能力)

3.The ability to publish events to registered listeners.Inherited from the {@link ApplicationEventPublisher} interface.(可以发布事件到注册监听器上的能力)

4.The ability to resolve messages, supporting internationalization.Inherited from the {@link MessageSource} interface.(处理消息的能力,支持国际化)

5.Inheritance from a parent context. Definitions in a descendant context will always take priority. This means, for example, that a single parent

context can be used by an entire web application, while each servlet has its own child context that is independent of that of any other servlet.

(可以继承一个上下文,定义一个派生上下文优先,例如,一个父上下文可以被整个网络应用,然而每一个servlet都有自己独立的子上下文。)
在这里插入图片描述
diagram

总结:举个简单的例子:整个应用比作一家企业的话,BeanFactory负责生产主管,而ApplicationContext则是CEO,总览全局,当然也包括生产主管BeanFactory。

BeanFactory和ApplicationContext对于bean后置处理器还有所不同,需要注意,ApplicationContext会自动检测在配置文件中实现了BeanPostProcessor接口的所有bean,

并把它们注册为后置处理器,然后在容器创建bean的适当时候调用它,因此部署一个后置处理器同部署其他的bean并没有什么区别。

而使用BeanFactory实现的时候,bean 后置处理器必须通过代码显式地去注册。

BeanFactory 和ApplicationContext
Bean 工厂(com.springframework.beans.factory.BeanFactory)是Spring 框架最核心的接口,它提供了高级IoC 的配置机制。
应用上下文(com.springframework.context.ApplicationContext)建立在BeanFactory 基础之上。
几乎所有的应用场合我们都直接使用ApplicationContext 而非底层的BeanFactory。

  1. BeanFactory负责读取bean配置文档,管理bean的加载,实例化,维护bean之间的依赖关系,负责bean的声明周期。
  2. ApplicationContext除了提供上述BeanFactory所能提供的功能之外,还提供了更完整的框架功能:

a. 国际化支持
b. 资源访问:Resource rs = ctx. getResource(“classpath:config.properties”), “file:c:/config.properties”
c. 事件传递:通过实现ApplicationContextAware接口
3. 常用的获取ApplicationContext的方法:
FileSystemXmlApplicationContext:从文件系统或者url指定的xml配置文件创建,参数为配置文件名或文件名数组
ClassPathXmlApplicationContext:从classpath的xml配置文件创建,可以从jar包中读取配置文件

WebApplicationContextUtils:从web应用的根目录读取配置文件,需要先在web.xml中配置,可以配置监听器或者servlet来实现

org.springframework.web.context.ContextLoaderListener

context

org.springframework.web.context.ContextLoaderServlet
1

这两种方式都默认配置文件为web-inf/applicationContext.xml,也可使用context-param指定配置文件:

contextConfigLocation

/WEB-INF/myApplicationContext.xml

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值