WebApplicationContextの使い分け
SpringMVCのメモ。
- Webアプリケーション全体で使うBean定義ファイルは、ContextLoaderListener(or ContextLoaderServlet)から呼び出す。
- サーブレット固有のBean定義ファイルは、DispatcherServletのパラメータとして渡す。
Webアプリ全体で使うBean定義ファイルを読み込んだApplicationContextは、WebApplicationContextUtils#getWebApplicationContext(ServletContext sc)で取得できる。
web.xml設定例。
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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"
version="2.4">
<display-name>SNPS Web Application</display-name>
<!-- ContextLoaderListenerで読み込まれるBean定義ファイル。-->
<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>
<!-- DispathcerServletはデフォルトで「Servlet名-servlet.xml」を読み込む。-->
<!-- この場合は「snps-servlet.xml」。-->
<servlet>
<servlet-name>snps</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>snps</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<!-- The Usual Welcome File List -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>