Spring Web ApplicationContext 갖고 오기
Spring Framework 기반의 애플리케이션에선 bean 객체를 갖고 오기 위해 GenericApplicationContext 설정, 참조한다.
그렇게 생성된 context 객체의 getBean 메소드를 통해 원하는 bean 객체를 참조할 수 있다.
스프링 기반의 웹 어플리케이션에선 bean 객체를 갖고 오기 위해 어떻게 context 객체를 참조해야 할까?
스프링 기반의 웹 어플리케이션을 만들기 위해 web.xml에 리스너를 생성해준다.
org.springframework.web.context.ContextLoaderListener 클래스이다.
ContextLoaderListener 이 클래스는 org.springframework.web.context.ContextLoader 클래스를 상속받아 구현된 것이다.
ContextLoader 클래스의 configureAndRefreshWebApplicationContext 메서드에서 다음과 같은 부분이 있다.
configLocationParam = sc.getInitParameter("contextConfigLocation");
web.xml을 통해 ServletContext initParameter로 등록해주는 이유이기도 하다. 바로 bean 설정을 참조하기 위해서이다.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/application-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
그럼 ContextLoaderListener 통해 만들어진 콘텍스트를 어떻게 참조해야 할까?
정답은 ContextLoaderListener 클래스가 상속받고 있는 ContextLoader 클래스에 있다.
org.springframework.web.context.ContextLoader 312줄에 정의된 메서드의 내용을 보면,
public static WebApplicationContext getCurrentWebApplicationContext() {
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl != null) {
WebApplicationContext ccpt = (WebApplicationContext)currentContextPerThread.get(ccl);
if (ccpt != null) {
return ccpt;
}
}
return currentContext;
}
currentContextPerThread 전역 변수(Map<ClassLoader, WebApplicationContext>)에 보관하고 있던 클래스 로더를 key값으로 WebApplicationContext를 반환하여 준다. 이 WebApplicationContext 통해 원하는 Bean 객체를 getBean 메서드를 이용하여 참조할 수 있다.
- 예제
WebApplicationContext context = ContextLoaderListener.getCurrentWebApplicationContext();
this.indexDataDAO = context.getBean("indexDataDAO", IndexData.class);