DispatcherServlet은 자체 구성을 위해 WebApplicationContext(ApplicationContext의 확장)를 기대합니다. WebApplicationContext에는 ServletContext와 연관된 Servlet에 대한 링크가 있습니다. 또한 ServletContext에 바인딩되어 있어 애플리케이션이 WebApplicationContext에 액세스해야 하는 경우 RequestContextUtils의 정적 메서드를 사용하여 이를 조회할 수 있습니다.

많은 애플리케이션의 경우, 단일 WebApplicationContext를 갖는 것이 간단하고 충분합니다. 하나의 루트 WebApplicationContext가 여러 DispatcherServlet(또는 다른 Servlet) 인스턴스에서 공유되고 서블릿 인스턴스 각각이 고유한 자식 WebApplicationContext 구성을 갖는 컨텍스트 계층을 갖는 것도 가능합니다.

루트 WebApplicationContext에는 일반적으로 데이터 저장소 및 여러 Servlet 인스턴스에서 공유해야 하는 비즈니스 서비스와 같은 인프라 빈이 포함됩니다. 이러한 빈은 효과적으로 상속되며 Servlet 특정 자식 WebApplicationContext에서 재정의(즉, 다시 선언)될 수 있습니다. 이 컨텍스트에는 일반적으로 해당 Servlet에 로컬인 빈을 포함하고 있습니다. 다음 이미지는 이러한 관계를 보여줍니다.

image.png

다음 예제에서는 WebApplicationContext 계층을 구성합니다.

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class<?>[] { RootConfig.class };
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class<?>[] { App1Config.class };
	}

	@Override
	protected String[] getServletMappings() {
		return new String[] { "/app1/*" };
	}
}

<aside>

TIP

애플리케이션 컨텍스트 계층이 필요하지 않으면 애플리케이션은 getRootConfigClasses()를 통해 모든 구성을 반환하고 getServletConfigClasses()에서 null을 반환할 수 있습니다.

</aside>

다음 예제는 web.xml에서 설정을 보여줍니다.

<web-app>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/root-context.xml</param-value>
	</context-param>

	<servlet>
		<servlet-name>app1</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/app1-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>app1</servlet-name>
		<url-pattern>/app1/*</url-pattern>
	</servlet-mapping>

</web-app>

<aside>

TIP

애플리케이션 컨텍스트 계층이 필요하지 않은 경우 애플리케이션은 "root" 컨텍스트만 구성하고 contextConfigLocation Servlet 매개변수를 비워 둘 수 있습니다.

</aside>