애플리케이션의 현재 상태, 환경 설정, 구성요소들의 집합을 관리하는 역할을 한다.
Servlet 3.0 이상 부턴 java code로 생성이 가능하다 아래를 보며Servlet 의 설정하는 방식을 볼 수 있다
public class ServletInitConfig implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
//① RootApplicationContext 생성 및 설정정보 등록
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(RootAppConfig.class);
//② RootApplicationContext 라이프사이클 설정
container.addListener(new ContextLoaderListener(rootContext));
//③ WebApplicationContext 생성 및 설정정보 등록
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.register(WebAppConfig.class);
//④ DispatcherServlet 생성 및 기타 옵션정보 설정
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
위 방법은 WebApplicationInitailizer 로 설정한 방식이다. onStartup 메서드의 인자값을 확인해 보면 ServletContext 타입의 변수를 파라미터로 받는 것을 볼 수 있다. 변수 명도 Container 인 것으로 보아 ServletContainer를 초기화하는 메서드이다.
RootApplication Context 생성 및 설정 살펴보기
@Configuration
@ComponentScan(basePackageClasses = {MysqlConfig.class, MemberRepository.class, MemberService.class})
public class RootAppConfig {
@Bean
public ObjectMapper objectMapper(){
return new ObjectMapper();
}
}
이때 ContextLoaderListenr 인스턴스 생성자 파라미터로 담아 등록하였는데 이 부분이 어떻게 라이프 사이클을 결정짓는지 아래 해당 클래스를 보면 알 수 있다.
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
public ContextLoaderListener() {
}
public ContextLoaderListener(WebApplicationContext context) {
super(context);
}
public void contextInitialized(ServletContextEvent event) {
this.initWebApplicationContext(event.getServletContext());
}
public void contextDestroyed(ServletContextEvent event) {
this.closeWebApplicationContext(event.getServletContext());
ContextCleanupListener.cleanupAttributes(event.getServletContext());
}
}