mvc : annotation-driven

Spring家族的配置中這兩個配置的意義,說具體點其實根據標籤的shecma就能看出來,mvc,主要就是爲了Spring MVC來用的,提供Controller請求轉發,json自動轉換等功能,而context這個主要是解決spring容器的一些註解。

從百度參考兩個帖子:

http://blog.csdn.net/sxbjffsg163/article/details/9955511

http://blog.sina.com.cn/s/blog_872758480100wtfh.html

<mvc:annotation-driven /> 是一種簡寫形式,完全可以手動配置替代這種簡寫形式,簡寫形式可以讓初學都快速應用默認配置方案。<mvc:annotation-driven /> 會自動註冊DefaultAnnotationHandlerMapping與AnnotationMethodHandlerAdapter 兩個bean,是spring MVC爲@Controllers分發請求所必須的。
並提供了:數據綁定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,讀寫XML的支持(JAXB),讀寫JSON的支持(Jackson)。
後面,我們處理響應ajax請求時,就使用到了對json的支持。
後面,對action寫JUnit單元測試時,要從spring IOC容器中取DefaultAnnotationHandlerMapping與AnnotationMethodHandlerAdapter 兩個bean,來完成測試,取的時候要知道是<mvc:annotation-driven />這一句註冊的這兩個bean。

context:annotation-config declares support for general annotations such as @Required, @Autowired, @PostConstruct, and so on.

<mvc:annotation-driven /> is actually rather pointless. It declares explicit support for annotation-driven MVC controllers (i.e.@RequestMapping, @Controller, etc), even though support for those is the default behaviour.

My advice is to always declare context:annotation-config, but don’t bother with <mvc:annotation-driven /> unless you want JSON support via Jackson.

在基於主機方式配置Spring的配置文件中,你可能會見到context:annotation-config/這樣一條配置,他的作用是式地向 Spring 容器註冊

AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、

PersistenceAnnotationBeanPostProcessor 以及 RequiredAnnotationBeanPostProcessor 這 4 個BeanPostProcessor。

註冊這4個 BeanPostProcessor的作用,就是爲了你的系統能夠識別相應的註解。

例如:

如果你想使用@Autowired註解,那麼就必須事先在 Spring 容器中聲明 AutowiredAnnotationBeanPostProcessor Bean。傳統聲明方式如下

如果想使用@ Resource 、@ PostConstruct、@ PreDestroy等註解就必須聲明CommonAnnotationBeanPostProcessor

如果想使用@PersistenceContext註解,就必須聲明PersistenceAnnotationBeanPostProcessor的Bean。

如果想使用 @Required的註解,就必須聲明RequiredAnnotationBeanPostProcessor的Bean。同樣,傳統的聲明方式如下:

一般來說,這些註解我們還是比較常用,尤其是Antowired的註解,在自動注入的時候更是經常使用,所以如果總是需要按照傳統的方式一條一條配置顯得有些繁瑣和沒有必要,於是spring給我們提供context:annotation-config/的簡化配置方式,自動幫你完成聲明。

使用註解一般都會配置掃描包路徑選項

<context:component-scan base-package=”XX.XX”/>

該配置項其實也包含了自動注入上述processor的功能,因此當使用 <context:component-scan/> 後,就可以將 <context:annotation-config/> 移除了。

<context:component-scan base-package=“org.fkit.controller”/>

mvc:annotation-driven/

mvc:default-servlet-handler/

/WEB-INF/content/ .jsp
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章