Spring/Spring MVC

[Spring MVC] 1-1. DispatcherServlet: Context Hierarchy

noahkim_ 2023. 10. 16. 00:53
프론트 컨트롤러
  • 애플리케이션에서 요청을 한 곳에서 받아서 적절한 컨트롤러나 핸들러로 라우팅하는 설계 패턴입니다.
  • Spring MVC는 프론트 컨트롤러 패턴 주위에 설계되었습니다.

 

DispatcherServlet
  • Spring MVC에서 프론트 컨트롤러 역할을 담당합니다.
    • 요청에 따라 적절한 컨트롤러나 뷰 리졸버, 예외 핸들러 등으로 라우팅하는 작업을 수행합니다.
  • Java 구성 방식이나 web.xml을 통해 할 수 있습니다.
    • DispatcherServlet은 일반적인 서블릿처럼 선언되고 매핑됩니다.
public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) {
        // Load Spring web application configuration
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(AppConfig.class);

        // Create and register the DispatcherServlet
        DispatcherServlet servlet = new DispatcherServlet(context);
        ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/app/*");
    }
}
<web-app>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

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

	<servlet>
		<servlet-name>app</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value></param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>app</servlet-name>
		<url-pattern>/app/*</url-pattern>
	</servlet-mapping>
</web-app>
ContextLoaderListener
  • 웹 애플리케이션의 생명주기와 함께 시작되어 Spring WebApplicationContext를 초기화하는 역할을 합니다.

 

context-param
  • contextConfigLocation : Spring 애플리케이션 컨텍스트의 구성 파일 위치를 지정합니다. 

 

1. Context Hierarchy

WebApplicationContext

  • ApplicationContext의 확장 버전으로 웹 애플리케이션에 특화된 버전입니다.
  • ServletContext와 연결되어 있습니다.
    • DispatcherServlet에게 ServletContext를 제공하는 역할을 합니다.
    • DispatcherServlet은 WebApplicationContext를 통해 필요한 구성 정보와 빈들을 얻습니다.
  • 많은 애플리케이션들은 단순히 하나의 WebApplicationContext만을 가집니다.
    • 애플리케이션 전반에 걸쳐 필요한 구성 정보나 빈들을 가지고 있습니다.

 

Context Hierarchy

  • 웹 애플리케이션의 복잡성에 따라 컨텍스트 계층 구조를 사용할 수 있습니다.
  • 복잡한 애플리케이션에서는 여러 개의 DispatcherServlet 인스턴스를 가질 수 있습니다.
    • 각 인스턴스는 WebApplicationContext를 가질 수 있으며, "Root" WebApplicationContext를 상속받습니다.

 

Root WebApplicationContext
  • 애플리케이션 전체에서 공유되어야 하는 인프라 구조 관련 빈들을 포함합니다.
  • 데이터 저장소, 비즈니스 서비스 등

 

자식 WebApplicationContext
  • 각 DispatcherServlet의 자식 WebApplicationContext는 주로 해당 서블릿에 특화된 빈들을 포함합니다.
  • 이 자식 컨텍스트는 root 컨텍스트에서 상속받은 빈들을 재정의 할 수 있습니다.

 

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/*" };
	}
}
<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>

 

 

 

출처