Controller에서 이미 만들어진 서비스나 그러한 부분들을 다시 사용하게 되는 경우 이 중복되는 코드를 어떻게 처리해야하는지 알아봤다.

바로 ContextLoaderListener를 사용하는 것이다. ContextLoaderListener는 WAS에서 서블릿 컨텍스트가 시작될 때 스프링에서 설정한 빈들을 Root WebApplicationContext에 적재한다.

이전에 알아본 DIspatcherServlet과 마찬가지로 WebApplicationContext을 가지지만 ContextLoaderListener의 WebApplicationContextDIspatcherServlet WebApplicationContext의 Root이다.

따라서 자식인 DIspatcherServlet WebApplicationContextContextLoaderListener의 WebApplicationContext에서 정의한 빈들을 사용할 수 있다.

또 아래 그림과 같이 ContextLoaderListener는 DAO, @Repository, @Service, @Entity와 같은 클래스들을 적재하고,

DIspatcherServlet은 Controller, ViewResolver, LocaleResolver, MVC 기반 인프라를 적재한다.

 

 

web.xml에 ContextLoaderListener 설정

  	<context-param>
		<param-name>contextClass</param-name>
		<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
	</context-param>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>kr.or.connect.guestbook.config.ApplicationConfig</param-value>
	</context-param>
	
	<!-- 
		ContextLoaderListener : 콘텍스트가 로딩될때 이거 읽어서 수행해라 
		ContextLoaderListener는 위에 두<context-param>을 참고한다.
	-->
  	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>

<listener>태그를 통해 ContextLoaderListener를 생성하고 <context-parm>을 통해 kr.or.connect.guestbook.config.ApplicationConfig 파일을 설정 파일로 등록하였다.

+ Recent posts