介绍
Spring
容器并不只有一个,Spring
自带了多个容器实现,可以归为两种类型。
bean工厂
(由org.springframework.beans.factory.BeanFactory
接口定义)是最简单的容器提供基本的DI支持。应用上下文
(由org.springframework.context.ApplicationContext
接口定义)基于BeanFactory构建,并提供应用框架级别的服务,例如从属性文件解析文本信息以及发布应用事件给感兴趣的事件监听者。
bean工厂
对于大多数应用来说往往太低级,因此,应用上下文
要比bean工厂
更受欢迎。
使用应用上下文
Spring
自带多种类型应用上下文。以下是最有可能遇到的。
AnnotationConfigApplicationContext
:从一个或多个基于Java的配置类中加载Spring
应用上下文。AnnotationConfigWebApplicationContext
:从一个或多个基于Java的配置类中加载Spring Web
应用上下文。ClassPathXmlApplicationContext
:从类路径下的一个或多个XML配置文件中加载上下文定义,把应用上下文的定义文件作为类资源。FileSystemXmlApplicationContext
:从文件系统下的一个或多个XML配置文件中加载上下文定义。XmlWebApplicationContext
:从Web应用下的一个或多个XML配置文件中加载上下文定义。
加载应用上下文:
// FileSystemXmlApplicationContext
ApplicationContext context = new FileSystemXmlApplicationContext("c:/knignt.xml");
// ClassPathXmlApplicationContext
ApplicationContext context = new ClassPathXmlApplicationContext("knignt.xml");
// AnnotationConfigApplicationContext
ApplicationContext context = new AnnotationConfigApplicationContext(com.knights.config.KnightConfig.class);
应用上下文准备就绪以后,可以调用上下文的getBean()方法从Spring
容器中获取bean。