Adding this annotation to an @Configuration class imports the Spring MVC configuration from WebMvcConfigurationSupport, e.g.:
1 | |
Similar to support found in <mvc:annotation-driven/> namespace.
To customize the imported configuration, implement the interface WebMvcConfigurer or more likely extend the empty method base class WebMvcConfigurerAdapter and override individual methods, e.g.:
1 | |
If WebMvcConfigurer does not expose some advanced setting that needs to be configured, consider removing the @EnableWebMvc annotation and extending directly from WebMvcConfigurationSupportor DelegatingWebMvcConfiguration, e.g.:
1 | |
原理分析
@EnableWebMvc实际导入了DelegatingWebMvcConfiguration
1 | |
1 | |
以下仅以interceptor为例分析原理,其他类似。
WebMvcConfigurationSupport中有如下拦截器相关的方法:
1 | |
DelegatingWebMvcConfiguration覆盖了addInterceptors(InterceptorRegistry)方法
1 | |
且
1 | |
WebMvcConfigurerComposite的addInterceptors实现如下:
1 | |
可见添加拦截器最终代理给了WebMvcConfigurer,以及WebMvcConfigurerAdapter。
1 | |
自定义拦截器通过InterceptorRegistry添加即可,参考如下:
1 | |
Spring boot中参见自动配置之WebMvcAutoConfiguration。
WebMvcConfigurationSupport
This is the main class providing the configuration behind the MVC Java config. It is typically imported by adding @EnableWebMvc to an application @Configuration class. An alternative more advanced option is to extend directly from this class and override methods as necessary remembering to add @Configuration to the subclass and @Bean to overridden @Bean methods. For more details see the Javadoc of @EnableWebMvc.
This class registers the following HandlerMappings:
RequestMappingHandlerMappingordered at 0 for mapping requests to annotated controller methods.HandlerMappingordered at 1 to map URL paths directly to view names.BeanNameUrlHandlerMappingordered at 2 to map URL paths to controller bean names.HandlerMappingordered atInteger.MAX_VALUE-1to serve static resource requests.HandlerMappingordered atInteger.MAX_VALUEto forward requests to the default servlet.
Registers these HandlerAdapters:
RequestMappingHandlerAdapterfor processing requests with annotated controller methods.HttpRequestHandlerAdapterfor processing requests withHttpRequestHandlers.SimpleControllerHandlerAdapterfor processing requests with interface-basedControllers.
Registers a HandlerExceptionResolverComposite with this chain of exception resolvers:
ExceptionHandlerExceptionResolverfor handling exceptions through @ExceptionHandlermethods.ResponseStatusExceptionResolverfor exceptions annotated with @ResponseStatus.DefaultHandlerExceptionResolverfor resolving known Spring exception types
Both the RequestMappingHandlerAdapter and the ExceptionHandlerExceptionResolver are configured with default instances of the following by default:
- A
ContentNegotiationManager - A
DefaultFormattingConversionService - A
LocalValidatorFactoryBeanif a JSR-303 implementation is available on the classpath - A range of
HttpMessageConverters depending on the 3rd party libraries available on the classpath.