Java/Spring

[스프링] Spring IoC 컨테이너, WebApplicationContext(DispatcherServlet, ContextLoaderListener), IoC 관련 @Annotation 설정

ImYena 2021. 9. 19. 16:04
728x90

Spring IoC 컨테이너

  • 자바 객체(빈)의 생명 주기(생성, 초기화, 서비스, 소멸) 관리
  • IoC의 대표적 예는 ServletContext
    • Servlet의 생명 주기를 관리

 

WebApplicationContext

  • Spring Web MVC에서 사용하는 IoC 컨테이너
  • ContextLoaderListenerDispatcherServlet에서 생성할 수 있음

 

IoC 관련 @Annotation 설정

<context:component-scan base-package="" use-default-filters="">

</context:component-scan>
  • base-package="" : Annotation을 찾기 시작할 패키지(하위 패키지 모두 검색)
  • use-default-filters="true" : 아래의 Annotation을 찾아 관리 빈으로 자동 생성
    • @Controller, @Service, @Repository, @Component
  • <context:include-filter> 태그
    • 관리 빈 생성에 포함될 Annotation 지정
  • <context:exclude-filter> 태그
    • 관리 빈 생성에 제외될 Annotation 지정

 

@Annotation

  • 빈 생성 및 소멸 관련 자동 인식 @Annotation
    • @PostConstruct, @PreDestroy
  • 의존성 주입 관련 자동 인식 @Annotation
    • @Resource, @Autowired, @Inject, @Value
  • MVC 관련 @Annotation
    • @RequestParam, @GetMapping, @PostMapping, @ModelAttribute
<mvc:annotation-driven/>

 

ContextLoaderListener

  • 공유 빈을 관리하는 WebApplicationContext 생성(web.xml)
    • DispatcherServlet에서 모두 관리하는 것이 아니라 공유할 수 있는 것들은 모아서 관리하는 짐꾼
  • 공유 리소스 정의
    • Service
    • Repository
  • 필요하지 않다면 생략 가능
  • 배치(Deploy/Undeploy) 감시자 역할
    • Deploy
      • .war를 WAS에 실행하도록 배치하는 것(WebApplication 배치 시 자동 실행)
    • Undeploy 
      • WAS에서 실행 중인 것을 중지시키고 빼버리는 것(WebApplication 배치 해제 시 자동 해제)

 

ContextLoaderListener 설정

- 모든 서블릿과 필터를 공유하는 경로

- 스프링 컨테이너 경로 정의

 

- 모든 서블릿과 필터가 공유하는 스프링 컨테이너 생성

- 위의 설정한 경로로 연결됨

 

 

ContextLoaderListener, IoC 관련 @Annotation 설정

<context:component-scan base-package="com.mycompany.webapp" use-default-filters="false">
	<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
	<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>

 

DispatcherServlet

  • 개별 빈을 관리하는 WebApplicationContext 생성(web.xml)
    • 요청 접수 및 컨트롤러 메소드 실행
    • View(JSP)로 이동(Forward)
  • 여러 개 생성 가능
  • 생략 불가능

 

DispatcherServlet 설정

- 애플리케이션의 요청(Request) 처리

 

DispatcherServlet, IoC 관련 @Annotation 설정

<annotation-driven/>

<context:component-scan base-package="com.mycompany.webapp">
	<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
	<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>

 


참고)

 

[스프링] 디스패처 서블릿 DispatcherServlet

디스패처 서블릿(DispatcherServlet) 서블릿 컨테이너 가장 앞단에서 HTTP 프로토콜로 들어오는 모든 요청을 가장 먼저 받아 적합한 컨트롤러에 위임해주는 *프론트 컨트롤러 DisparcherServlet은 공통적인

imyena.tistory.com

 

728x90
반응형