天天看点

在web中使用Spring容器一、问题描述二、解决

一、问题描述

Spring的容器对象在项目中只能有一个,那么如何保证只创建一个,创建后如何获得?

二、解决

1、保证只创建一个

方法:

(1)Spring的解决方法是放入到servletContext域中,因为该对象的生命周期是从项目启动到项目关闭

(2)创建一个监听器,在该对象创建的时候创建Spring容器,销毁的时候关闭容器

步骤:

(1)Spring已经写好了该监听器,我们只要配置就可以了(导包——web包)

(2)无论什么方式创建Spring容器,都需要application.xml文件的位置;该监听器中有保存application.xml的变量,变量名可以在源码中查看(包为web包),该监听器继承了ContextLoader类,在ContextLoader类中有键名。

<!-- Spring随项目启动 -->
<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring配置文件位置 -->
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
</context-param>
           

2、获得applicationContext容器

该容器被创建到了servletcontext域中,我们可以通过getAttribute获得,但是键名过长,不容易记住,不过Spring写了一个工具类可以帮我们从servletContext中获得applicationContext:

//1、在action中获得servletContext对象
ServletContext sc = ServletActionContext.getServletContext();
//2、从servletContext中获取applicationContext对象
WebApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
           

继续阅读