[英]Loading context in Spring using 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");
您還可以相對於當前類路徑指定上下文位置,這可能是更可取的
<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,並將控制器分離出來,將解析程序bean查看到WebApplicationContext。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.