SpringMVC之mvc:annotation-driven和@EnableWebMvc

版权声明:版权所有,谢绝转载。 https://blog.csdn.net/tales522/article/details/89736753

在SpringMVC中,往往xml配置最后都能被注解替代,在配置Controller接受请求时,使用xml配置的方式是添加
<mvc:annotation-driven/>
这个配置会自动注册三个类
RequestMappingHandlerMapping
RequestMappingHandlerAdapter
ExceptionHandlerExceptionResolver
以支持使用注解@Controller的注解方法(如@RequestMapping、@ExceptionHandler)来处理request,并开启一系列默认功能设置,有了这个配置,就能将所有请求映射到@Controller修饰的handler上,以及对应的@RequestMapping上,仅仅配置这个,可以处理数据接口,但是无法映射静态资源,这时我们再添加一个配置即可
<mvc:default-servlet-handler />
这个配置会注入一个org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler类型的handler。这个handler会将所有请求过滤,如果是注册过的uri就分派到对应的@Controller,如果不是就给到容器默认的Servlet处理,一般容器都会有默认的请求处理Servlet且名字为default。这两个配置就能将处理所有请求了,包括静态资源的。
    这种配置现在完全可以使用注解来替换了
@EnableWebMvc这个注解会注入一个DelegatingWebMvcConfiguration配置类型,DelegatingWebMvcConfiguration继承于WebMvcConfigurationSupport,使用了这个Spring Boot的自动装配就不会发生了,我们能用的,只有WebMvcConfigurationSupport提供的若干个配置。其实不使用@EnableWebMvc注解也是可以实现配置Webmvc,只需要将配置类继承于WebMvcConfigurationSupport类即可。结论就是:

当使用@EnableWebMvc时,加载的是WebMvcConfigurationSupport中的配置项。
当不使用@EnableWebMvc时,使用的是WebMvcAutoConfiguration引入的配置项。

有时候我们需要自己定制一些项目的设置,可以有以下几种使用方式:
1、@EnableWebMvc+extends WebMvcConfigurationAdapter,在扩展的类中重写父类的方法即可,这种方式会屏蔽springboot的@EnableAutoConfiguration中的设置
2、extends WebMvcConfigurationSupport,在扩展的类中重写父类的方法即可,这种方式会屏蔽springboot的@EnableAutoConfiguration中的设置
3、extends WebMvcConfigurationAdapter/WebMvcConfigurer,在扩展的类中重写父类的方法即可,这种方式依旧使用springboot的@EnableAutoConfiguration中的设置

使用总结:

Spring Boot 默认提供Spring MVC 自动配置,不需要使用@EnableWebMvc注解
如果需要配置MVC(拦截器、格式化、视图等) 请使用添加@Configuration并实现WebMvcConfigurer接口.不要添加@EnableWebMvc注解。
@EnableWebMvc 只能添加到一个@Configuration配置类上,用于导入Spring Web MVC configuration
最后,如果Spring Boot在classpath里看到有 spring webmvc 也会自动添加@EnableWebMvc。

猜你喜欢

转载自blog.csdn.net/tales522/article/details/89736753