在Spring MVC应用程序中是否可以使用web.xml加载上下文的方法?
来自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");
您还可以相对于当前类路径指定上下文位置,这可能更可取。
<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>
classpath*
的问题的博客文章,链接在这里:http://www.gridshore.nl/2008/05/13/spring-application-context-loading-tricks/。 - DavidS您还可以在定义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中。