springBoot关于WebXXXAutoConfiguration自动配置失效问题

由于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");
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值