실전 개발자를 위한 Spring Framework Day14 (2회차)
Context 분리와 전략
- Context = 스프링 컨테이너
1. Servlet Context vs Root Application context
Servlet Context
- DispatcherServlet
- 웹의 요청을 최초로 접수
- 설정파일을 이용해 ServletContext(스프링 컨테이너) 로딩
- Spring-MVC와 관련 있는 빈을 설정 => web과 관련된 빈을 관리
- Controllers, ViewResolver, HandlerMapping 등록(Web관련 Bean)
- 서블릿에서만 이용되는 컨텍스트
- 타 서블릿과 공유하기 위한 Bean들은 Root Context에 등록해놓고 사용해야 한다
- DispatcherServlet은 자신만의 컨텍스트를 생성, 초기화하고 동시에 Root Context를 찾아서 자신의 부모 컨텍스트로 사용한다
Root Context
- Spring-MVC와 분리되어 빈을 관리하고 싶을 때 사용 => web과 무관한 빈을 관리
- 일반적으로 Servlet context와 Root context를 분리하여 운용
- Servlet Context 간에는 Bean을 공유할 수 없으므로 공유가 필요한 Bean은 Root Context에 등록한다
-
Services, Repositories, DB 등록(Web관련 이외 Bean)
- 전체 계층구조에서 최상단에 위치한 컨텍스트
- 서로 다른 서블릿 컨텍스트에서 공유해야 하는 Bean들을 등록해놓고 사용할 수 있다
- 웹 어플리켄이션 전체에 적용 가능한 Db연결, 로깅기능 등에 이용
- Servlet Context에 등록된 Bean은 이용 불가능하다
=> Servlet Context와 동일한 Bean이 있을 경우 Servlet Context Bean이 우선된다
- 하나의 컨텍스트에 정의된 AOP 설정은 다른 컨텍스트의 빈에는 영향을 미치지 않는다
2. 컨텍스트 분리 전략
Servlet Context
- @Controller
<context:component-scan base-package="패키지 경로" use-default-filters="false">
<!-- @Controller 붙은 것들을 포함하도록 한다 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 패키지 경로 예시: kr.co.company.hello -->
Root Context
- @Service - 트랜잭션 적용(with AOP)
- @Repository
<context:component-scan base-package="패키지 경로">
<!-- @Controller 붙은 것들을 제외하도록 한다 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>