当前位置: 首页 > news >正文

玩转springboot之springboot扩展SpringMVC

springboot扩展SpringMVC

springboot为springmvc提供了很多自动配置,虽然适用于大部分应用,但是不一定适合你的应用

WebMvcConfigurer

WebMvcConfigurer是用来全局定制化Spring boot的MVC特性,可以通过实现WebMvcConfigurer接口来配置应用的MVC全局特性,但是由于该接口方法很多,全部实现比较麻烦,所以一般是继承WebMvcConfigurerAdapter类,该类实现了WebMvcConfigurer接口,并全部提供了空实现,可以选择需要自定义的来进行重写的

WebMvcConfigurerAdapter类在springboot2.x中就不建议使用了,因为java8中接口可以存在default方法,使得WebMvcConfigurerAdapter没有意义,直接实现WebMvcConfigurer接口即可

既保留自动配置又有扩展配置

根据官网的描述,如果想要扩展SpringBoot对于SpringMVC的配置而又保留SpringBoot对SpringMVC的自动配置,可以编写一个配置类(@Configuration)继承WebMvcConfigurerAdapter类,但是不能标注@EnableWebMvc

如果是使用的springmvc框架而非springboot框架的话,必须有@EnableWebMvc注解,否则重写WebMvcConfigurerAdapter的方法无效

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    // 配置拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        super.addInterceptors(registry);
    }
    
    // 时间、数字格式化
    @Override
    public void addFormatters(FormatterRegistry registry) {
    }
    
    // 消息解析器
   // 对应xml中的 <mvc:annotation-driven>
    //    <mvc:message-converters register-defaults="true">
    //        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
    //            <constructor-arg value="UTF-8"/>
    //        </bean>
    //    </mvc:message-converters>
    //</mvc:annotation-driven>
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    }

    // 验证器  用以处理所有注解了@Valid的元素或注解了@Validated 的控制器方法参数
    @Override
    public Validator getValidator() {
        return null;
    }
  
   // 静态资源过滤
   // 对应xml 中的 <mvc:resources location="/WEB-INF/templates/" mapping="/templates/**"/>
   @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    }
   
  // 视图解析器 
  // 对应于在xml中配置 viewResolver的bean
   @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
    }
    
}
原因

为什么继承WebMvcConfigurerAdapter就可以扩展springmvc的配置呢?

在WebMvcAutoConfiguration类中有一个bean是WebMvcAutoConfigurationAdapter

 @Configuration
 @Import(EnableWebMvcConfiguration.class)
 @EnableConfigurationProperties(
{ WebMvcProperties.classResourceProperties.class })
 public static class WebMvcAutoConfigurationAdapter extends WebMvcConfigurerAdapter 
{

使用@Import来引入的这个组件中有一个方法,会将所有的WebMvcConfigurer类都加入到configurers中

public void setConfigurers(List<WebMvcConfigurer> configurers) {
  if (!CollectionUtils.isEmpty(configurers)) {
   this.configurers.addWebMvcConfigurers(configurers);
  }
 }

而WebMvcConfigurerAdapter就实现于WebMvcConfigurer

public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {

使用自定义配置抛弃自动配置

在上述配置类上加上@EnableWebMvc注解,就可以完全取代springboot对于springmvc的自动配置

原因

至于为什么会这样,看一下@EnableWebMvc这个注解就知道了

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc 
{
}

这个注解会引入一个DelegatingWebMvcConfiguration组件,而这个类是继承自WebMvcConfigurationSupport

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

接下来看一下WebMvcAutoConfiguration的加载条件是什么

@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.classDispatcherServlet.class,
  WebMvcConfigurerAdapter.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter(
{ DispatcherServletAutoConfiguration.class,
  ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration 
{

@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)

可以看到是在没有WebMvcConfigurationSupport这个bean的时候才会加载,所以打破了这个条件导致WebMvcAutoConfiguration不会生效

之前看到有人使用WebMvcConfigurationSupport来进行自定义配置,这里也要注意一下,如果使用了WebMvcConfigurationSupport的话,WebMvcAutoConfiguration是不会生效的,也就是说抛弃了webMvc的自动配置

https://zhhll.icu/2021/框架/springboot/基础/5.扩展SpringMVC/

本文由 mdnice 多平台发布

相关文章:

  • Elasticsearch实战教程: 如何在海量级数据中进行快速搜索
  • 行业模板|DataEase旅游行业大屏模板推荐
  • SpringMVC页面加载不出来,静态资源全部自动https
  • 反射--通俗易懂
  • ModuleNotFoundError: No module named ‘_sysconfigdata_x86_64_conda_linux_gnu‘
  • YOLO在目标检测与视频轨迹追踪中的应用
  • 使用hadoop进行数据分析
  • library source does not match the bytecode for class SpringApplication
  • Ajax异步请求 axios
  • 深⼊理解 JVM 底层原理、垃圾回收机制,能通过mat、jstat进行JVM参数调优
  • 关于5G和卫星
  • 昇思第7天
  • 递归算法练习
  • Qt的信号与槽机制底层原理
  • 核方法总结(三)———核主成分(kernel PCA)学习笔记
  • 【Under-the-hood-ReactJS-Part0】React源码解读
  • Android框架之Volley
  • CSS相对定位
  • Docker 1.12实践:Docker Service、Stack与分布式应用捆绑包
  • Docker 笔记(1):介绍、镜像、容器及其基本操作
  • Java 9 被无情抛弃,Java 8 直接升级到 Java 10!!
  • JS基础篇--通过JS生成由字母与数字组合的随机字符串
  • MySQL的数据类型
  • Netty源码解析1-Buffer
  • React 快速上手 - 07 前端路由 react-router
  • Redis的resp协议
  • Spring技术内幕笔记(2):Spring MVC 与 Web
  • 大数据与云计算学习:数据分析(二)
  • 分布式熔断降级平台aegis
  • 海量大数据大屏分析展示一步到位:DataWorks数据服务+MaxCompute Lightning对接DataV最佳实践...
  • 盘点那些不知名却常用的 Git 操作
  • 如何进阶一名有竞争力的程序员?
  • 实战|智能家居行业移动应用性能分析
  • 使用 5W1H 写出高可读的 Git Commit Message
  • 译有关态射的一切
  • 用jquery写贪吃蛇
  • “十年磨一剑”--有赞的HBase平台实践和应用之路 ...
  • #NOIP 2014# day.2 T2 寻找道路
  • #vue3 实现前端下载excel文件模板功能
  • #中国IT界的第一本漂流日记 传递IT正能量# 【分享得“IT漂友”勋章】
  • (2009.11版)《网络管理员考试 考前冲刺预测卷及考点解析》复习重点
  • (Mac上)使用Python进行matplotlib 画图时,中文显示不出来
  • (PyTorch)TCN和RNN/LSTM/GRU结合实现时间序列预测
  • (Redis使用系列) Springboot 实现Redis消息的订阅与分布 四
  • (Spark3.2.0)Spark SQL 初探: 使用大数据分析2000万KF数据
  • (windows2012共享文件夹和防火墙设置
  • (zt)基于Facebook和Flash平台的应用架构解析
  • (二)hibernate配置管理
  • (非本人原创)我们工作到底是为了什么?​——HP大中华区总裁孙振耀退休感言(r4笔记第60天)...
  • (深度全面解析)ChatGPT的重大更新给创业者带来了哪些红利机会
  • (一)python发送HTTP 请求的两种方式(get和post )
  • (转)shell调试方法
  • .libPaths()设置包加载目录
  • .NET Core 中插件式开发实现
  • .net 怎么循环得到数组里的值_关于js数组