SpringBoot专题学习Part15:SpringBoot下的扩展和全面接管SpringMVC

在不结合SpringBoot时 要配置SpringMVC时 须写配置文件来配置路径转发和拦截器之类的组件
例如:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <mvc:view-controller path="/hello" view-name="success"/>
    
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/hello"/>
            <bean></bean>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

那么SpringBoot中没有配置文件 该如何实现上述功能

其实 只需编写一个配置类(用@Configuration注解标注)
该类的类型为WebMvcConfigurerAdapter 且不能标注@EnableWebMvc注解


扩展SpringMVC

扩展的意思就是 既保留了所有的自动配置 也能使用自己扩展的配置

需要创建自定义的配置类
例:

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // 设置视图映射规则
        // 当浏览器发送/gotosuccess请求 跳转到success页面(页面也是由模板引擎的视图解析器来解析的)
        registry.addViewController("/gotosuccess").setViewName("success");
    }
}

这样 需要视图映射的时候 就无须用Controller来帮助跳转了

原理:

继承的WebMvcAutoConfiguration是SpringMVC在SpringBoot中对应的的自动配置类

该类有个@Import(EnableWebMvcConfiguration.class)注解
即 该类在做其他自动配置时会导入名为EnableWebMvcConfiguration的类
该类的父类里面 会自动装配 从容器中获取所有的WebMvcConfigurer
然后将WebMvcConfigurer相关配置都调用一遍
这样 容器中所有的WebMvcConfigurer都会一起起作用

如此 SpringMVC的自动配置和自己写的的扩展配置都会起作用


全面接管SpringMVC

若要完全掌控SpringMVC 只需要添加@EnableWebMvc这一个注解
放弃SpringBoot对SpringMVC的自动配置 全部自己配置
所有的SpringMVC的自动配置全部失效

例:

@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    ...
    }
}
原理:
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
    ...
}

@EnableWebMvc注解底层导入了一个名为DelegatingWebMvcConfiguration的类

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
    ...
}

而 在自动配置类中 添加了一个@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)注解
意即 当容器中没有WebMvcConfigurationSupport组件时 该自动配置类才生效

DelegatingWebMvcConfiguration继承了WebMvcConfigurationSupport
因此自动配置类就失效了

又由于 导入的WebMvcConfigurationSupport只有SpringMVC最基本的功能 因此 全部的组件都需要自己配置


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值