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