系列八、SpringBoot中自定义SpringMVC配置

一、概述

        作为Spring家族的明星产品,SpringBoot极大地简化了程序员的日常开发,提高了开发效率。我们很容易得借助于SpringBoot就可以快速开发业务代码。一般情况下,公司的日常开发都是基于web服务的,我们在使用idea等工具初始化一个springboot项目时,一般都会在pom.xml中加入 spring-boot-starter-web 依赖,引入了这个依赖后,springmvc相关的依赖就都引入进来并通过springboot的自动化配置给我们配置好了,如下:

        但是,真实的项目环境下,系统自带的配置不一定能满足我们的实际需求,这就需要我们结合实际业务进行自定义配置了。

二、SpringMVC配置相关的类

        WebMvcConfigurer(Interface)、WebMvcConfigurerAdapter(Class,新版本已废弃)、WebMvcConfigurationSupport(Class)、@EnableWebMvc(注解)

2.1、WebMvcConfigurerAdapter

        WebMvcConfigurerAdapter是springboot 1.x中定义的一个类,在1.x版本中,自定义springmvc的配置就可以通过继承WebMvcConfigurerAdapter实现的,这个抽象类本身实现了WebMvcConfigurer接口,2.x及以上版本已废弃,源码如下:

/**
 * An implementation of {@link WebMvcConfigurer} with empty methods allowing
 * subclasses to override only the methods they're interested in.
 *
 * @author Rossen Stoyanchev
 * @since 3.1
 */
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {
    
    //...

}

2.2、WebMvcConfigurer

        WebMvcConfigurer是一个接口,接口中的方法和 WebMvcConfigurerAdapter 中定义的空方法其实一样,所以用法上来说,基本上没有差别,从 Spring Boot 1.x 切换到 Spring Boot 2.x ,只需要把继承类改成实现即可,在springboot2.x及以上版本,如果我们有自定义SpringMVC的需求,可以通过实现 WebMvcConfigurer 接口来配置,源码如下:

/**
 * Defines callback methods to customize the Java-based configuration for
 * Spring MVC enabled via {@code @EnableWebMvc}.
 *
 * <p>{@code @EnableWebMvc}-annotated configuration classes may implement
 * this interface to be called back and given a chance to customize the
 * default configuration.
 *
 * @author Rossen Stoyanchev
 * @author Keith Donald
 * @author David Syer
 * @since 3.1
 */
public interface WebMvcConfigurer {

    // ...

}

 2.3、WebMvcConfigurationSupport

        WebMvcConfigurationSupport是一个类,一般用于ssm(spring+springmvc+mybatis)的项目中,自定义类通过继承WebMvcConfigurationSupport,可以在不写springmvc.xml配置的情况下,实现对mvc的配置,例如:

注意事项:

        WebMvcConfigurationSupport禁止在springboot中使用!因为在springboot中如果使用了WebMvcConfigurationSupport,将会导致SpringBoot中的MVC自动配置失效,SpringBoot中的mvc的自动化配置类是WebMvcAutoConfiguration,其源码如下:

        很明显的可以看到SpringBoot中WebMvcAutoConfiguration生效的前提是当前资源目录下无WebMvcConfigurationSupport,所以在在springboot中禁止使用WebMvcConfigurationSupport!!!

2.4、@EnableWebMvc

        @EnableWebMvc是一个注解, 它的作用是启用WebMvcConfigurationSupport,通过2.3的源码分析,所以在springboot中也不建议使用,因为它也会导致SpringBoot的WebMvcAutoConfiguration失效,源码如下:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值