what <mvc:annotation-driven /> does

 

<mvc:annotation-driver /> is a shorthand to simplify manual configuration. To know what it does its parsing class is good.

There is a MvcNamespaceHandler under the spring-webmvc package, which is dedicated to processing the tags under the mvc namespace. (You can see here that the so-called namespace is configured for classification processing). The init() method of MvcNamespaceHandler registers many parsers, among which the AnnotationDrivenBeanDefinitionParser parser is used to parse "annotation-driven".

 

You can see that the parser does the following:

1. Register the following HandlerMapping:

RequestMappingHandlerMapping

BeanNameUrlHandlerMapping

 

2. Register the following HandlerAdapter:

RequestMappingHandlerAdapter

HttpRequestHandlerAdapter

SimpleControllerHandlerAdapter

 

And register several HandlerExceptionResolver, AntPathMatcher. (we don't pay attention)

 

We pay more attention to HandlerMapping and HandlerAdapter. In fact, even if we don't configure it at all, the DispatcherServlet class will read the DispatcherServlet.properties resource file to do some default configuration, in DispatcherServlet.properties

HandlerMapping is configured by default:

BeanNameUrlHandlerMapping和DefaultAnnotationHandlerMapping

The default configuration of HandlerAdapter is:

HttpRequestHandlerAdapter、SimpleControllerHandlerAdapter和AnnotationMethodHandlerAdapter

 

 

When the process of parsing <mvc:annotation-driver /> configures the RequestMappingHandlerAdapter, it will automatically register some MessageConverters to convert the result into the desired data format when returning. For example, sometimes you need to convert the result into json and put it back in ResponseBody, you need to register MappingJackson2HttpMessageConverter. The parsing class checks if the path exists

"com.fasterxml.jackson.databind.ObjectMapper" and "com.fasterxml.jackson.core.JsonGenerator" two classes (existing in jackson's jar package), if they exist, register MappingJackson2HttpMessageConverter. Therefore, you must add the relevant package, and then choose to configure <mvc:annotation-driver /> or manually configure

<bean id="jsonConverter"

class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>

<bean

class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">

<property name="messageConverters">

<list>

<ref bean="jsonConverter" />

</list>

</property>

</bean>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326134792&siteId=291194637