SpringBoot如何扩展与全面接管SpringMVC
1、在实际开发过程中,仅仅是SpringBoot集成的功能使用SpringMVC是仅仅不够的,比如: <mvc:view-controller path=/success view-name=success/> <mvc:default-servlet-handler/> <mvc:annotation-driven></mvc:annotation-driven>
2、如果你想要扩展SpringMVC配置的功能,比如interceptors,formatter,view controller,你能够添加一个实现WebMvcConfiguerAdapter类@Configration类,并且不能标注@EnableWebMvc注解。
3、使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能,比如浏览器发送/bg请求来到success视图。代码中的双引号已经被删除,请自行加上package com.gwolf.config;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configurationpublic class MyMvcConfig extends WebMvcConfigurerAdapter{ @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController(/bg).setViewName(success); }}
4、这样既保留了所有的自动配置,也能为我们扩展自己的配置。这样实现的原理是:1、WebMvcAutoConfiguration是SpringMVC的自动配置类。2、在做其他自动配置时会导入:@Import(EnableWebMvcConfiguration.class)
5、EnableWebMvcConfiguration会加载容器中所有的WebMvcConfigurer一起起作用。这样SpringMVC的自动配置和我们的配置类也会被调用。
6、如果SpringBoot对SpringMVC的自动配置不需要,所有都是我们自己配置,只需要增加注解@EnableWebMvc注解。这样所有的SpringMVC自动配置都会失效。
7、为什么加了@EnableWebMvc自动配置就失效了。