Context Hierarchy

Dev.Hammy·2024년 3월 26일
0

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

많은 애플리케이션의 경우 단일 WebApplicationContext를 갖는 것만으로도 간단하고 충분합니다. 하나의 루트 WebApplicationContext가 각각 자체 하위 WebApplicationContext 구성을 갖는 여러 DispatcherServlet(또는 다른 Servlet) 인스턴스에서 공유되는 컨텍스트 계층 구조를 갖는 것도 가능합니다. 컨텍스트 계층 기능에 대한 자세한 내용은 ApplicationContext의 추가 기능을 참조하세요.

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

다음 예에서는 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/*" };
	}
}

[Tip]
애플리케이션 컨텍스트 계층 구조가 필요하지 않은 경우 애플리케이션은 getRootConfigClasses()를 통해 모든 구성을 반환하고 getServletConfigClasses()에서 null을 반환할 수 있습니다. 다음 예에서는 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>

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

0개의 댓글