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

70

在Spring MVC应用程序中是否可以使用web.xml加载上下文的方法?

3个回答

121

来自Spring文档

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了解更多信息。


2
如何访问上下文?你是说上下文会在应用程序启动时随着Spring Context一起加载吗?请澄清,因为我是Spring的新手。感谢您的回复。 - Ganesh
这里是与WebApplicationContextUtils相关的最新API链接。https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/context/support/WebApplicationContextUtils.html - Ajitesh

34

您还可以相对于当前类路径指定上下文位置,这可能更可取。

<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>

“*” 的意义是什么?没有它就无法工作:“从 ServletContext 资源解析 XML 文档时出现 IOException [/>classpath:/applicationContext.xml];嵌套异常是 java.io.FileNotFoundException:无法打开 ServletContext 资源 [/>classpath:/applicationContext.xml]”。 - DavidS
1
我刚刚发现了一篇关于classpath*的问题的博客文章,链接在这里:http://www.gridshore.nl/2008/05/13/spring-application-context-loading-tricks/。 - DavidS

17

您还可以在定义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加载的上下文实际上是DispatcherServlet专门加载的上下文的父级上下文。因此,您可以将所有业务服务、数据访问或存储库bean加载到应用程序上下文中,并将控制器、视图解析器bean分离到WebApplicationContext中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接