在Spring中使用web.xml加载上下文

有没有一种方法可以在Spring MVC应用程序中使用web.xml加载上下文?

从春季文档

Spring可以很容易地集成到任何基于Java的Web框架中。 您只需要在web.xml中声明ContextLoaderListener ,并使用contextConfigLocation来设置要加载的上下文文件。

<context-param>

 <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext*.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> 

然后,您可以使用WebApplicationContext获取bean的句柄。

 WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext()); SomeBean someBean = (SomeBean) ctx.getBean("someBean"); 

请参阅http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html了解更多信息;

您也可以指定相对于当前类path的上下文位置,这可能是优选的

 <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本身时加载上下文( WebApplicationContext

  <servlet> <servlet-name>admin</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring/*.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>admin</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> 

而不是( ApplicationContext

 <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext*.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> 

或者可以一起做。

仅仅使用WebApplicationContext的缺点是,它只会为这个特定的Spring入口点( DispatcherServlet )加载上下文,与上面提到的方法一样,上下文将被加载到多个入口点(例如Webservice Servlet, REST servlet等)

ContextLoaderListener加载的上下文将事实上成为专门为DisplacherServlet加载的上下文。 所以基本上你可以在应用程序上下文中加载所有的业务服务,数据访问或存储库bean,并分离出你的控制器,将parsing器bean视为WebApplicationContext。