엔지니어로 가는 길

Spring Web MVC에서 사용하는 context들 본문

프로그래밍/Spring

Spring Web MVC에서 사용하는 context들

탐p슨 2020. 3. 3. 14:44
728x90

이 글에서는 Spring Web MVC의 context에 대해 알아볼 것이다.

 

WebApplicationContext? ApplicationContext? ServletContext?

 

먼저 Context들을 정리하는 게 좋을 것 같다.

 

ApplicationContext는 Spring에서 만든 인터페이스로 말그대로 애플리케이션에 대한 context를 가지고 있다.

 

WebApplicationContext란 Spring의 ApplicationContext를 확장한 인터페이스로, 웹 애플리케이션에서 필요한 몇 가지 기능을 추가한 인터페이스다. 예를 들면 WebApplicationContext의 구현체는 getServletContext라는 메소드를 통해 ServletContext를 얻을 수 있다.

 

ServletContext는 Servlet API에서 제공하는 context로 모든 servlet이 공유하는 context이다. Spring Web MVC에서는 ServletContext가 WebApplicationContext를 가지고 있다. 아래의 그림과 같이 Serlvet Context가 WebApplication을 감싸고 있다. 아래에서 Root Applicaition Context와 Servlet Application Context 1~3 모두 WebApplicationContext이다.

 

 

https://stackoverflow.com/questions/33163441/spring-why-root-application-context-and-servlet-application-context-are-cre

 

 

WebApplicationContext는 ServletContext와 이 context와 관련있는 Servlet에 접근할 수 있다.

 

 

또한 WebApplicationContext는 ServletContext에 묶여있기 때문에 RequestContextUtils의 정적 메소드를 통해 WebApplicationContext에 접근할 수 있다.

 

 

즉, WebApplicationContext과 ServletContext은 서로에게 접근할 수 있다.

 

DispatcherServlet은 WebApplicationContext를 이용하여 자신을 설정한다

 

지난 글에서 말한 것과 마찬가지로 DispatcherServlet도 결국 Servlet이다. 따라서 다른 Servlet과 마찬가지로 자바 설정이나 web.xml에 있는 설정에 따라 정의되어야 하고 매핑되어야 한다. DispatcherServlet은 WebApplicationContext를 이용하여 자신을 설정한다.

 

Context Hierarchy

 

Context는 계층구조(부모 자식 관계, 상속 관계)를 가질 수 있다. 다시 말해 하나의 root WebApplicationContext 밑에 여러 개의 child WebApplicationContext를 갖는 것도 가능하다.

 

공통되는 자원은 root WebApplicationContext에 두고,  DispatcherServlet 또는 Servlet 마다 자신만의 child WebApplicationContext를 갖도록 만든다. root WebApplicationContext은 대개 data repository나 비즈니스 서비스와 같이 다른 Servlet 객체에서도 필요한 infrastructure 빈들을 가지고 있고, child WebApplicationContext는 자신의 Servlet에서만 사용할 빈들을 가지고 있다. 물론 root WebApplicationContext의 빈들은 필요한 경우 자식 WebApplicationContext에서 override하여 사용할 수 있다.

 

 

 

참고자료

https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc

https://stackoverflow.com/questions/33163441/spring-why-root-application-context-and-servlet-application-context-are-cre

https://stackoverflow.com/questions/11708967/what-is-the-difference-between-applicationcontext-and-webapplicationcontext-in-s

 

728x90
Comments