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。
- BeanFactory负责读取bean配置文档,管理bean的加载,实例化,维护bean之间的依赖关系,负责bean的声明周期。
- 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
org.springframework.web.context.ContextLoaderServlet
1
这两种方式都默认配置文件为web-inf/applicationContext.xml,也可使用context-param指定配置文件:
contextConfigLocation/WEB-INF/myApplicationContext.xml