剖析context:component-scan/、mvc:annotation-dri...
2019獨角獸企業重金招聘Python工程師標準>>>
自己看了官方文檔,也到網上查了下,目前理解如下: ?<context:component-scan/>和<mvc:annotation-driven/>:
<mvc:annotation-driven/>相當于注冊了DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter兩個bean,配置一些messageconverter。即解決了@Controller注解的使用前提配置。?
<context:annotation-config/>是對包進行掃描,實現注釋驅動Bean定義,同時將bean自動注入容器中使用。即解決了@Controller標識的類的bean的注入和使用。?
一開始我在寫配置的時候,只寫了<context:component-scan/>,并沒有使用<mvc:annotation-driven/>,servlet攔截*.do,.do請求可以被正確捕捉和處理。代碼如下?
mvc-servlet.xml?
Java代碼??
web.xml?
Java代碼??
后來為了解決靜態資源訪問的問題,servlet改成了攔截所有請求,即/,并添加了默認的servlet,這時候*.do請求不能被控制器捕捉了,頁面錯誤為404。直到添加了<mvc:annotation-driven/>之后,.do請求才又能被正確捕捉和處理。代碼如下?
mvc-servlet.xml?
Java代碼??
web.xml?
Java代碼??
是什么原因造成這種區別的呢?為什么一開始沒用<mvc:annotation-driven/>的時候可以,添加了默認servlet之后就不行了呢?
<context:annotation-config/>和<context:component-scan/>:
在基于主機方式配置Spring的配置文件中,你可能會見到<context:annotation-config/>這樣一條配置,他的作用是式地向?Spring?容器注冊
AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、
PersistenceAnnotationBeanPostProcessor?以及?RequiredAnnotationBeanPostProcessor?這?4?個BeanPostProcessor。
注冊這4個?BeanPostProcessor的作用,就是為了你的系統能夠識別相應的注解。
例如:
如果你想使用@Autowired注解,那么就必須事先在?Spring?容器中聲明?AutowiredAnnotationBeanPostProcessor Bean。傳統聲明方式如下
<bean?class="org.springframework.beans.factory.annotation.?AutowiredAnnotationBeanPostProcessor?"/>?
如果想使用@ Resource?、@ PostConstruct、@ PreDestroy等注解就必須聲明CommonAnnotationBeanPostProcessor
如果想使用@PersistenceContext注解,就必須聲明PersistenceAnnotationBeanPostProcessor的Bean。
如果想使用?@Required的注解,就必須聲明RequiredAnnotationBeanPostProcessor的Bean。同樣,傳統的聲明方式如下:
<bean?class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>?
一般來說,這些注解我們還是比較常用,尤其是Antowired的注解,在自動注入的時候更是經常使用,所以如果總是需要按照傳統的方式一條一條配置顯得有些繁瑣和沒有必要,于是spring給我們提供<context:annotation-config/>的簡化配置方式,自動幫你完成聲明。
???不過,呵呵,我們使用注解一般都會配置掃描包路徑選項
<context:component-scan?base-package=”XX.XX”/>?
????該配置項其實也包含了自動注入上述processor的功能,因此當使用?<context:component-scan/>?后,就可以將?<context:annotation-config/>?移除了。
轉載于:https://my.oschina.net/u/1012289/blog/129298
總結
以上是生活随笔為你收集整理的剖析context:component-scan/、mvc:annotation-dri...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 神舟十三号径向对接有多难?空间站充当路由
- 下一篇: 游戏id取名鬼才好听又搞笑名字798个