由于WebMvcConfigurerAdapter过时,采用继承WebMvcConfigurationSupport类重写addViewControllers方法来实现请求拦截直接映射成视图的功能
@Configuration
public class Myconfig extends WebMvcConfigurationSupport{
@Override
protected void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
}
这个方法有一个坑,关于静态资源路径等默认配置都会失效,需要我们自己去手动配置,为什么会有这种情况,我们看一下springBoot关于自动配置的源码
@Configuration
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, ValidationAutoConfiguration.class})
public class WebMvcAutoConfiguration {
其中@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})这一块的意思是当前配置类是在容器中找不到WebMvcConfigurationSupport这样一个类时才会启用,而我们自己的配置继承了WebMvcConfigurationSupport这个类,所以springBoot关于mvc的自动配置失效,由我们全面接管,而@EnableWebMvc这个注解为什么只要一添上,就会由我们全面接管web的配置也是这个原因,@EnableWebMvc这个注解向我们导入了DelegatingWebMvcConfiguration.class这个类
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({DelegatingWebMvcConfiguration.class})
public @interface EnableWebMvc {
而它又继承了WebMvcConfigurationSupport,所以同样的自动默认配置不起作用
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
由于springBoot中的默认配置有大量的判断,所以我们在自己写配置类时一定要注意是否跟自己需要的springBoot的默认配置有冲突,导致SpringBoot的配置的判断生效,默认配置不起作用。
对于以上配置实现映射视图的功能,推荐使用
实现WebMvcConfigurer这个接口
@Configuration
public class myMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
}