SpringMVC—標籤

annotation-driven缺省註冊類的改變 

Spring 3.0.x中使用了annotation-driven後,缺省使用DefaultAnnotationHandlerMapping 來註冊handler method和request的mapping關係。 AnnotationMethodHandlerAdapter來在實際調用handlermethod前對其參數進行處理。 

 

在spring mvc 3.1中,對應變更爲 
DefaultAnnotationHandlerMapping -> RequestMappingHandlerMapping 
AnnotationMethodHandlerAdapter -> RequestMappingHandlerAdapter 
AnnotationMethodHandlerExceptionResolver -> ExceptionHandlerExceptionResolver 

以上都在使用了annotation-driven後自動註冊。 
  而且對應分別提供了AbstractHandlerMethodMapping , AbstractHandlerMethodAdapter和 AbstractHandlerMethodExceptionResolver以便於讓用戶更方便的實現自定義的實現類。

<mvc:annotation-driven/>相當於註冊了DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter兩個bean,配置一些messageconverter。即解決了@Controller註解的使用前提配置。



在Spring3.0中

在Spring3.0.5這個版本上,<mvc:annotation-driven/>聲明是沒有 defaultAnnotationHandlerMapping這個屬性的,對於@ResultMapping標籤的解析,是寫死了必須用 "org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping” 這個類來處理的。

在Spring 2.5中

那麼Spring是如何解析<mvc:annotation-driven/>標籤的呢?

首先,必須要有一個繼承自“org.springframework.beans.factory.xml.NamespaceHandlerSupport”的類,在其init方法中,註冊自己的解析器,註冊mvc解析器的類爲MvcNamespaceHandler。一般針對每個元素,都有一個解析器,比如:針對annotation-driven,就有一個解析器:AnnotationDrivenBeanDefinitionParser。

解析器必須實現org.springframework.beans.factory.xml.BeanDefinitionParser接口,這個接口只有一個parse方法,它有兩個參數,第一個參數org.w3c.dom.Element就是我們在xml文件中聲明的<mvc:annotation-driven/>結點,拿到這個結點信息,就可以開始具體的業務了。

Spring怎麼知道處理mvc開頭的標籤就調用MvcNamespaceHandler中註冊的解析器呢?

需要有一個"mvc”<–>MvcNamespaceHandler這樣一個映射關係,那麼這個映射關係在哪裏呢?就在META-INF目錄下的spring.handlers:源文件中的內容:

http\://www.springframework.org/schema/mvc=
org.springframework.web.servlet.config.MvcNamespaceHandler

這裏定義了只要是http\://www.springframework.org/schema/mvc命名空間的標籤,就使用org.springframework.web.servlet.config.MvcNamespaceHandler中的解析器。

頭文件裏說的http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd,並不是真的到網上去下載這個文件,在spring.schemas文件中,定義了它指向org/springframework/web/servlet/config/spring-mvc-3.0.xsd這個文件(在jar包裏)。

所以,在Spring中,想使用自己的命名空間:

1、首先需要一個xsd文件,來描述自定義元素的命名規則,並在再Spring的配置文件的<benas>頭中引用它。

2、然後需要實現一個BeanDefinitionParser接口,在接口的parse方法中,解析將來在Spring配置文件中出現的元素。(如果xsd聲明可以有多個元素,需呀實現多個BeanDefinitionParser接口)

3、最後需要繼承一個NamespaceHandlerSupport類,在它的init方法中,調用registerBeanDefinitionParser方法,將待解析的xml元素與解析器綁定。

4、在META-INF目錄下,創建spring.schemas、spring.handlers文件,建立最高級的映射關係以便Spring進行處理。

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