Spring容器是Spring框架当中的一个核心模块,用来管理对象。在基于Spring的应用中,你的对象生存在Spring的容器中,Spring容器负责创建对象,装配对象和配置他们,并且管理对象的整个生命周期。
Spring容器类型
Spring容器并不是只有一个,而是有多个,大体上可以归为两种类型。
1. bean工厂:由org.springframework.beans.factoryeanFactory接口定义,是最简单的容器,提供基本的DI(依赖注入)
2. 应用上下文:由org.springframework.context.ApplicationContext接口定义,提供应用框架级别的服务,所以比bean工厂更受欢迎
应用上下文
Spring自带了多种类型的应用上下文,常用的可能有这么几个:
- AnnotationConfigApplicationContext:从一个或多个基于Java的配置类中加载Spring应用上下文
- AnnotationConfigWebApplicationContext:从一个或多个基于Java的配置类中加载Spring Web应用上下文
- ClassPathXmlApplicationContext:从类路径下的一个或多个XML配置文件中加载上下文定义,把应用上下文的定义文件作为类资源
- FileSystemXmlapplicationContext:从文件系统下的一个或多个XML配置文件中加载上下文定义
- XmlWebApplicationContext:从Web应用下的一个或多个XML配置文件中加载上下文定义
启动Spring容器
启动容器常用的几种方式:
手动启动Spring容器:
1 | ApplicationContext ac = new ClassPathXmlApplicationContext(config); |
在Web项目中:
- 用监听器的方式来启动Spring容器:
在web.xml中1
2
3
4
5
6
7
8<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>1
2
3
4
5
6
7
8<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener> 用servlet方式来启动Spring容器:这种方式,spring3.0以后不再支持,建议使用监听器方式1
2
3
4
5<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>单元测试时启动Spring容器:
在用Junit进行单元测试时可以用@ContextConfiguration注解来启动Spring容器除了junit4和spring的jar包,还需要spring-test.jar1
2@ContextConfiguration(locations = "classpath:applicationContext.xml")
@ContextConfiguration(locations ={"/applicationContext.xml"})