<mvc:annotation-driven /> 是一種簡寫形式,徹底能夠手動配置替代這種簡寫形式,簡寫形式可讓初學都快速應用默認配置方案。<mvc:annotation-driven /> 會自動註冊DefaultAnnotationHandlerMapping與AnnotationMethodHandlerAdapter 兩個bean,是spring MVC爲@Controllers分發請求所必須的。css
這句話我在不少帖子都看到過,我本身的項目自己使用的Spring MVC 3.2,實際上在3.1以後,<mvc:annotation-driven />註冊的類發生了變化html
Spring Framework 3.1 introduces a new set of support classes for processing requests with annotated controllers:java
RequestMappingHandlerMapping
web
RequestMappingHandlerAdapter
spring
ExceptionHandlerExceptionResolver
express
These classes are a replacement for the existing:json
DefaultAnnotationHandlerMapping
spring-mvc
AnnotationMethodHandlerAdapter
mvc
AnnotationMethodHandlerExceptionResolver
app
The above registers a RequestMappingHandlerMapping
, a RequestMappingHandlerAdapter
, and an ExceptionHandlerExceptionResolver
(among others) in support of processing requests with annotated controller methods using annotations such as @RequestMapping
, @ExceptionHandler
, and others.
It also enables the following:
Spring 3 style type conversion through a ConversionService instance in addition to the JavaBeans PropertyEditors used for Data Binding.
Support for formatting Number fields using the @NumberFormat
annotation through the ConversionService
.
Support for formatting Date, Calendar, Long, and Joda Time fields using the @DateTimeFormat
annotation.
Support for validating @Controller inputs with @Valid
, if a JSR-303 Provider is present on the classpath.
HttpMessageConverter support for @RequestBody
method parameters and @ResponseBody
method return values from @RequestMapping
or @ExceptionHandler
methods.
This is the complete list of HttpMessageConverters set up by mvc:annotation-driven:
ByteArrayHttpMessageConverter
converts byte arrays.
StringHttpMessageConverter
converts strings.
ResourceHttpMessageConverter
converts to/from org.springframework.core.io.Resource
for all media types.
SourceHttpMessageConverter
converts to/from a javax.xml.transform.Source
.
FormHttpMessageConverter
converts form data to/from a MultiValueMap<String, String>
.
Jaxb2RootElementHttpMessageConverter
converts Java objects to/from XML — added if JAXB2 is present on the classpath.
MappingJackson2HttpMessageConverter
(or MappingJacksonHttpMessageConverter
) converts to/from JSON — added if Jackson 2 (or Jackson) is present on the classpath.
AtomFeedHttpMessageConverter
converts Atom feeds — added if Rome is present on the classpath.
RssChannelHttpMessageConverter
converts RSS feeds — added if Rome is present on the classpath.
這是摘取的官方文檔,能夠看出,註冊的類已經變成了RequestMappingHandlerMapping和
RequestMappingHandlerAdapter。
我以前在不知道的時候,使用AnnotationMethodHandlerAdapter 進行配置,結果在有<mvc:annotation-driven />存在的狀況下,我本身配置的AnnotationMethodHandlerAdapter 怎麼都不起做用,因而去掉了<mvc:annotation-driven />標籤,手動註冊了AnnotationMethodHandlerAdapter ,和DefaultAnnotationHandlerMapping。結果引起了其餘問題,好比文件沒法上傳的問題。
閱讀文檔發現Spring提供了基於<mvc:annotation-driven />自定義messageConverters的方法,以下所示:
下面展現我本身的配置