
2.2 Spring IoC容器
由2.1节得知,实现控制反转的是Spring IoC容器。Spring IoC容器的设计主要是基于BeanFactory和ApplicationContext两个接口。
2.2.1 BeanFactory
BeanFactory由org.springframework.beans.factory.BeanFactory接口定义,它提供了完整的IoC服务支持,是一个管理Bean的工厂,主要负责初始化各种Bean。BeanFactory接口有多个实现类,其中比较常用的是org.springframework.beans.factory.xml.XmlBeanFactory,该类会根据XML配置文件中的定义来装配Bean(有关Bean的知识将在本书第3章讲解)。
在创建BeanFactory实例时需要提供XML文件的绝对路径。例如可以将第1章ch1应用中main方法的代码修改如下:

使用BeanFactory实例加载Spring配置文件在实际开发中并不多见,读者了解即可。
2.2.2 ApplicationContext
ApplicationContext是BeanFactory的子接口,也称为应用上下文,由org.springframework. context.ApplicationContext接口定义。ApplicationContext接口除了包含BeanFactory的所有功能以外,还添加了对国际化、资源访问、事件传播等内容的支持。
创建ApplicationContext接口实例通常有以下3种方法:
① 通过ClassPathXmlApplicationContext创建
ClassPathXmlApplicationContext将从类路径目录(src根目录)中寻找指定的XML配置文件,例如第1章ch1应用中main方法的代码:

② 通过FileSystemXmlApplicationContext创建
FileSystemXmlApplicationContext将从指定文件的绝对路径中寻找XML配置文件,找到并装载完成ApplicationContext的实例化工作。例如,可以将第1章ch1应用中main方法的代码修改如下:

采用绝对路径的加载方式将导致程序的灵活性变差,一般不推荐使用。因此,通常在Spring的Java应用中采取通过ClassPathXmlApplicationContext类来实例化ApplicationContext容器的方式,而在Web应用中,ApplicationContext容器的实例化工作将交给Web服务器完成。
③ 通过Web服务器实例化ApplicationContext容器
在Web服务器实例化ApplicationContext容器时,一般使用基于org.springframework. web.context.ContextLoaderListener的实现方式(需要将spring-web-5.0.2.RELEASE.jar复制到WEB-INF/lib目录中),此方法只需在web.xml中添加如下代码:
