Spring/Spring 웹 MVC
[스프링 웹 MVC] WebMvcConfigurer 인터페이스
메성
2020. 4. 7. 01:44
반응형
WebMvcConfigurer 인터페이스
//0. 애플리케이션 컨텍스트 설정
public class WebApplication implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setServletContext(servletContext);
context.register(WebConfig.class);
context.refresh();
DispatcherServlet dispatcherServlet = new DispatcherServlet(context);
ServletRegistration.Dynamic app = servletContext.addServlet("app", dispatcherServlet);
app.addMapping("/app/*");
}
}
//1. @EnableWebMvc 사용
@EnableWebMvc
//2. @EnableWebMvc 내부
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({DelegatingWebMvcConfiguration.class})
public @interface EnableWebMvc {
}
//3. import 내부
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
}
-
@EnableWebMvc는 DispatcherServlet의 기본 전략을 사용하는 것이 아니라 DelegatingWebMvcConfiguration을 import하는데, import하는 설정은 Delegation 구조로 되어있다.
-
Delegation 구조로 되어 있는 이유는, 확장성을 좋게하기 위함이다.
-
이로 인해, 우리가 원하는 대로 쉽게 커스텀 할 수 있는 것이다.
-
이 때, 커스텀 하기 위해서는 우리는 인터페이스를 확장해야 하는데, 이 때 필요한 인터페이스가 WebMvcConfigurer이다.
@Configuration @ComponentScan @EnableWebMvc public class WebConfig implements WebMvcConfigurer { }
-
-
WebMvcConfigurer 인터페이스를 사용하면 ViewResolver도 쉽게 커스텀 할 수 있다.
@Configuration @ComponentScan @EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Override public void configureViewResolvers(ViewResolverRegistry registry) { registry.jsp("/WEB-INF/", ".jsp"); } }
-
WebMvcConfigurer는 스프링 부트에서도 사용되니, WebMvcConfigurer 내부를 까보는 것도 매우 유용할 것이다.
-
WebMvcConfgiurer의 구현으로 인해 DispatcherServlet을 간편하게 커스텀할 수 있으므로, 스프링 부트 없이 스프링 부트를 사용하는 방법이라고 불리는 것이다.
반응형