Spring 注解 @EnableWebMvc 工作原理

本文分析所用源代码基于Spring 5.1.3 RELEASE

概述

通常我们使用注解@EnableWebMvc在一个@Configuration注解的配置类上,用于对Spring MVC进行配置。用法如下所示 :

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
    // 根据需求,重写 WebMvcConfigurer 接口所定义的各个方法从而定制Spring MVC
    @Override
    public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) {
        // ... 
    }

    // ...
}

那么@EnableWebMvc注解到底是怎么工作的 ?

实际上,@EnableWebMvc仅仅导入一个类DelegatingWebMvcConfiguration,而DelegatingWebMvcConfiguration则继承自WebMvcConfigurationSupportWebMvcConfigurationSupport的作用是提供缺省的Spring MVC配置,具体体现形式是向容器登记一组Spring MVC运行时使用的bean

DelegatingWebMvcConfiguration则增强了WebMvcConfigurationSupport,它本身也是一个配置类,会被注入一组WebMvcConfigurer,这组WebMvcConfigurer会被DelegatingWebMvcConfiguration用于定制Spring MVC配置。

所以如果想对WebMvcConfigurationSupportSpring MVC的缺省配置进行定制,可以让@EnableWebMvc所注解的配置类实现接口WebMvcConfigurer所定义的方法。也就是我们上面例子所演示的做法。

源代码

package org.springframework.web.servlet.config.annotation;


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
// 使用注解@Import 引入代理配置类 DelegatingWebMvcConfiguration
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}

作为一个注解,@EnableWebMvc的代码并不复杂,可以看出,其主要的作用是通过@Import注解导入Spring MVC代理配置类DelegatingWebMvcConfiguration

总结

从上可见,@EnableWebMvc注解的主要作用是引入DelegatingWebMvcConfiguration配置类。而对Spring MVC配置的主要工作,由WebMvcConfigurationSupport和用户提供的WebMvcConfigurer配置器实现。

相关文章

Spring MVC 代理配置类 DelegatingWebMvcConfiguration

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值