스프링 ContextLoaderListener 의 역할

FRAMEWORK/SPRING 2014. 9. 25. 12:03

계층별로 나눈 xml 설정파일이 있다고 가정할 때,
web.xml에서 모두 load되도록 등록할 때 사용.
서블릿이전에 서블릿 초기화하는 용도록 쓰이며, 
contextConfigLocation라는 파라미터를 쓰면, 
Context Loader가 load할 수 있는 설정파일을 여거개 쓸 수 있다.

web.xml에 저 문장이 빠지게 되면 default로,
/WEB-INF/applicationContext.xml (spring 설정파일) 을 쓰게 된다.

[web.xml]

<context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
           /WEB-INF/mars-ibatis.xml 
           /WEB-INF/mars-service.xml 
      </param-value>
</context-param>

<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


출처 - http://northface.tistory.com/entry/contextConfigLocation-and-orgspringframeworkwebcontextContextLoaderListener%EC%8A%A4%ED%94%84%EB%A7%81-%EC%84%A4%EC%A0%95%ED%8C%8C%EC%9D%BC%EC%9D%84-%EC%9D%BD%EA%B8%B0




<servlet>

    <servlet-name>aController</servlet-name>

    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>

    <param-name>contextConfigLocation</param-name>

    <param-value>/WEB-INF/a-servlet.xml</param-value>

        </init-param>

     <load-on-startup>1</load-on-startup>

</servlet>


<servlet>

    <servlet-name>bController</servlet-name>

    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>

    <param-name>contextConfigLocation</param-name>

    <param-value>/WEB-INF/b-servlet.xml</param-value>

        </init-param>

     <load-on-startup>1</load-on-startup>

</servlet>


위와 같은 경우 DispatcherServlet 은 각가 별도의 webapplicationcontext를 생성한다.

두 context 는 독립적이므로 각각의 설정파일에서 생성한 빈을 서로 사용할 수 없다.(공유X)


이때 동시에 필요한 의존성(공통빈) 이 있어야 하는 경우

ContextLoaderListener 을 사용하여 공통으로 사용할 빈을 설정할 수 있다.


<listener>

     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>


<context-param>

    <param-name>contextConfigLocation</param-name>

    <param-value>

        /WEB-INF/applicationContext.xml

        /WEB-INF/applicationContext_dao.xml

    </param-value>

</context-param>


ContextLoaderListener 와 DispatcherServlet 은 각각 webapplicationcontext 를 생성하는데

ContextLoaderListener 가 생성한 컨텍스트가 root 컨텍스트가 되고 DispatcherServlet  생성한 인스턴스는

root 컨텍스트를 부모로 하는 자식 컨텍스트가 된다.


자식 컨텍스트들은 root 컨텍스트의 설정 빈을 사용 할 수 있다.

그러기에 ContextLoaderListener 을 이용 공통빈 설정 가능.


출처 - http://blog.daum.net/_blog/BlogTypeView.do?blogid=0Tqpx&articleno=217&categoryId=0&regdt=20130911110427

: