1 创建工程
创建动态的Web工程。
2 导包
导入核心包:
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
导入依赖包:
commons-logging-1.1.3.jar
导入Web包:
spring-web-4.0.0.RELEASE.jar
3 配置文件
3.1 创建beans.xml配置文件
在src目录下创建Spring的配置文件。
3.2 在web.xml文件中加入监听器
在Web项目中使用Spring,需要配置监听器,在服务器启动的时候创建IOC容器,并放在application域中。
同时还要配置应用的上下文参数,指明配置文件的位置。
添加配置:
<!-- 应用上下文参数:可以通过ServletContext中getInitParameter("contextConfigLocation");方法获取。 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans*.xml</param-value>
</context-param>
<!-- 监听器:在服务器启动时,监听ServletContext对象创建和销毁,并创建和销毁IOC容器。 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
查看ContextLoaderListener的源码可以发现,该类实现了ServletContextListener接口,可以监听ServletContext对象的初始化和销毁。
通过配置contextConfigLocation参数可以指定在初始化ServletContext对象时加载的配置文件。
如果在Web环境下使用,那么创建的IOC容器的对象类型是XmlWebApplicationContext,如果不是在Web环境下使用,那么创建的IOC容器类型是ClassPathXmlApplicationContext。
4 获取容器
在Web环境下使用Spring容器,需要通过ServletContext获取:
ServletContext servletContext = request.getServletContext();
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);