WebApplicationInitilaizer를 이용한 컨텍스트 등록

Posted by 단순대왕 Spring/init : 2016. 1. 15. 11:35

스프링 3.1에서는 ServletContainerInitializer를 이용하면 스프링 컨텍스트 설정과 등록 작업에 자바 코드를 이용할 수 있다.

서블릿 3.0은 웹 어플리케이션 구성에 web.xml 파일만을 단독으로 사용하던 것에서 탈피해, 설정 방식을 모듈화해서 관리하는 방법을 도입.

프레임워크 모듈에서 직접 서블릿 컨텍스트를 초기화할 수 있게 도와주는 ServletContainerInitializer 같은 API가 제공.

스프링 웹 모듈 내에 ServletContainerInitializer를 구현한 클래스가 포함되어 있고, WebApplicationInitializer 인터페이스를 구현한 클래스를 찾아 

컨텍스트의 초기화 작업을 위임한다.

WebApplicationInitializer를 구현한 클래스를 만들어두면 웹 어플리케이션이 시작될 때 onStartup() 메소드가 자동으로 실행된다.

이때 메소드 파라미터로 ServletContext 오브젝트가 전달되는데, 이를 이용해 필요한 컨텍스트 등록 작업을 수행. [출처: 토비의 스프링]


public class WebAppInitializer implements WebApplicationInitializer {

@Override

public void onStartup(ServletContext servletContext) throws ServletException {

AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();

rootContext.setConfigLocation("com.test.common.config");


ContextLoaderListener contextLoaderListener = new ContextLoaderListener(rootContext);

servletContext.addListener(contextLoaderListener);


AnnotationConfigWebApplicationContext servlet = new AnnotationConfigWebApplicationContext();

ServletRegistration.Dynamic dispatcher = servletContext.addServlet("app", new DispatcherServlet(servlet));

dispatcher.setLoadOnStartup(2);

dispatcher.setInitParameter("enablePooling", "false");

dispatcher.addMapping("/app/*");

dispatcher.addMapping("*.json");

}

}

'Spring > init' 카테고리의 다른 글

eclipse와 maven 연동  (0) 2016.01.07
maven local repository 사용방법  (0) 2014.11.12
  
 «이전 1 2 3 4 5 6 7 ··· 77  다음»