您的位置:首页 > 编程语言 > Java开发

在Web应用中创建Spring容器的两种方式

2016-11-05 16:46 507 查看
使用spring的web应用时,不用手动创建spring容器,而是通过配置文件声明式地创建spring容器,因此,在web应用中创建spring容器有如下两种方式:
一.直接在web.xml文件中配置spring容器
二.利用第三方MVC框架的扩展点,创建spring容器

其实第一种方式最为常见。
为了让spring容器随web的应用的启动而自动启动,有如下两种方法

    1.利用ServletContextListener实现

    2.采用load-on-startup Servlet实现
 
对于利用ServletContextListener实现方式,操作及说明如下
    spring提供ServletContextListener的一个实现类ContextLoadListener,该类可以作为Listener使用,会在创建时自动查找web-inf/applicationContext.xml文件,因此,如果只有一个配置文件,并且名为applicationContext.xml,只需要在web.xml文件中加入如下配置即可

[html] view
plain copy

 print?

<listener>  

  <listener-class>  

      org.springframework.web.context.ContextLoaderLister  

  </listener-class>  

</listener>  

如果有多个配置文件需要载入,则考虑用<context-param>元素来确定配置文件的文件名。ContextLoadListenter加载时,会查找名为contextConfigLocation的参数。因此,配置context-param时,参数名应该是contextConfigLocation
 
带多个配置文件的web.xml文件如下

[html] view
plain copy

 print?

<?xml version="1.0" encoding="UTF-8"?>  

<web-app version="2.4"  

 xmlns="http://java.sun.com/xml/ns/j2ee"  

 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  

 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee  

 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  

  

   

 <context-param>  

  <!-- 参数名为contextConfigLocation -->  

  <param-name>contextConfigLocation</param-name>  

  <!-- 配置多个文件之间,以","隔开 -->  

  <param-value>/WEB-INF/actionContext.xml,/WEB-INF/appContext.xml,/WEB-INF/daoContext.xml</param-value>  

 </context-param>  

   

 <!-- 采用listener创建ApplicationContext实例 -->  

 <listener>  

  <listener-class>  

   org.springframework.web.context.ContextLoaderLister  

  </listener-class>  

 </listener>  

</web-app>  

如是没有通过contextConfigLocation指定配置文件,spring会自动查找applicationContext.xml文件;如果有contextConfigLocation,则利用该参数确定的配置文件,如果无法找到合适的配置文件,spring将无法正常初始化
    spring根据bean定义创建WebApplicationContext对象,并将其保存在web应用的ServletContext中。大部分情况下,应用的Bean无须感受到ApplicationContext的存在,只要利用ApplicationContext的IOC容器
如果需要在应用中获取ApplicationContext实例,可以通过如下代码获取
//获取当前web应用的spring的容器
WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(ServletContext);

二.利用第三方MVC框架的扩展点,创建spring容器

      Struts有一个扩展点PlugIn,spring正是利用了PlugIn这个扩展点,从而提供了与Struts的整合。。spring提供了PlugIn的实现类org.springframework.web.struts.ContextLoadPlugIn,这个实现类可作为struts的PlugIn配置,Struts框架启动时,将自动创建Spring容器

     为了利用struts的PlugIn创建Spring容器,只需要在struts配置文件struts-config.xml中增加如下片段即可

 <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">

   <set-property property="contextConfigLocation" value="/WEB-INF/actionContext.xml,/WEB-INF/appContext.xml,/WEB-INF/daoContext.xml" />

 </plug-in>

      其中,指定contextConfigLocation属性值时,即可以指定一个spring配置文件的位置,可以指定多个spring配置文件的位置
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息