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 WebMvcConfigurationSupport
or 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 HandlerMapping
s:
RequestMappingHandlerMapping
ordered at 0 for mapping requests to annotated controller methods.HandlerMapping
ordered at 1 to map URL paths directly to view names.BeanNameUrlHandlerMapping
ordered at 2 to map URL paths to controller bean names.HandlerMapping
ordered atInteger.MAX_VALUE-1
to serve static resource requests.HandlerMapping
ordered atInteger.MAX_VALUE
to forward requests to the default servlet.
Registers these HandlerAdapter
s:
RequestMappingHandlerAdapter
for processing requests with annotated controller methods.HttpRequestHandlerAdapter
for processing requests withHttpRequestHandler
s.SimpleControllerHandlerAdapter
for processing requests with interface-basedController
s.
Registers a HandlerExceptionResolverComposite
with this chain of exception resolvers:
ExceptionHandlerExceptionResolver
for handling exceptions through @ExceptionHandler
methods.ResponseStatusExceptionResolver
for exceptions annotated with @ResponseStatus
.DefaultHandlerExceptionResolver
for 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
LocalValidatorFactoryBean
if a JSR-303 implementation is available on the classpath - A range of
HttpMessageConverter
s depending on the 3rd party libraries available on the classpath.