スプリングMVC設定(3):WebMvcConfiguratorインタフェース


3.WebMvcConfiguratorインタフェース
@EnableWebMvcが提供するカスタマイズ可能なインタフェースで、「D e l e g a tingWebMvcConfiguration.class」および「WebMvcConfigurationSupport.class」をカスタマイズできます.
@Configuration 
@EnableWebMvc 
public class WebConfig implements WebMvcConfigurer { 
    @Override 
    public void configureViewResolvers(ViewResolverRegistry registry) { 
        registry.jsp("/WEB-INF/", ".jsp"); 
    } 
}
@Configuration
@ComponentScan
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/", ".jsp");
    }
}
@Controller
public class HelloController {

    @Autowired
    HelloService helloService;

    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        return "Hello, " + helloService.getName();
    }

    @GetMapping("/sample")
    public void sample(){
    }
}
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/*");
    }
}
これにより,@EnableWebMvc++implementWebMvcConfigurator+implementWebApplicationInitializer(DispatcherServiceRegistration)はSpringブートを使用せずにSpring MVCを使用することができる.
@EnableWebMvc++implements WebMvcConfiguratorを使用すると、直接登録空よりも簡単に空にすることができます.
リファレンス
  • インフラストラクチャ:SpringWeb MVC(白旗船)