The NoteBook of EricKong

            BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
            611 Posts :: 1 Stories :: 190 Comments :: 0 Trackbacks

           在xml配置了這個標簽后,spring可以自動去掃描base-pack下面或者子包下面的java文件,如果掃描到有@Component @Controller@Service等這些注解的類,則把這些類注冊為bean

          注意:如果配置了<context:component-scan>那么<context:annotation-config/>標簽就可以不用再xml中配置了,因為前者包含了后者。另外<context:annotation-config/>還提供了兩個子標簽

          1.        <context:include-filter>

          2.       <context:exclude-filter>

          在說明這兩個子標簽前,先說一下<context:component-scan>有一個use-default-filters屬性,改屬性默認為true,這就意味著會掃描指定包下的全部的標有@Component的類,并注冊成bean.也就是@Component的子注解@Service,@Reposity。所以如果僅僅是在配置文件中這么寫

          <context:component-scan base-package="tv.huan.weisp.web"/>

           Use-default-filter此時為true那么會對base-package包或者子包下的所有的進行java類進行掃描,并把匹配的java類注冊成bean。

           

           可以發現這種掃描的粒度有點太大,如果你只想掃描指定包下面的Controller,該怎么辦?此時子標簽<context:incluce-filter>就起到了勇武之地。如下所示

          <context:component-scan base-package="tv.huan.weisp.web .controller">  

          <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>   

          </context:component-scan>  

          這樣就會只掃描base-package指定下的有@Controller下的java類,并注冊成bean

          但是因為use-dafault-filter在上面并沒有指定,默認就為true,所以當把上面的配置改成如下所示的時候,就會產生與你期望相悖的結果(注意base-package包值得變化)

          <context:component-scan base-package="tv.huan.weisp.web ">  

          <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>   

          </context:component-scan>  

          此時,spring不僅掃描了@Controller,還掃描了指定包所在的子包service包下注解@Service的java類

          此時指定的include-filter沒有起到作用,只要把use-default-filter設置成false就可以了。這樣就可以避免在base-packeage配置多個包名這種不是很優雅的方法來解決這個問題了。

          另外在我參與的項目中可以發現在base-package指定的包中有的子包是不含有注解了,所以不用掃描,此時可以指定<context:exclude-filter>來進行過濾,說明此包不需要被掃描。綜合以上說明

          Use-dafault-filters=”false”的情況下:<context:exclude-filter>指定的不掃描,<context:include-filter>指定的掃描

          posted on 2014-08-13 11:22 Eric_jiang 閱讀(203) 評論(0)  編輯  收藏 所屬分類: Spring
          主站蜘蛛池模板: 南宫市| 紫金县| 天柱县| 方山县| 万载县| 石棉县| 任丘市| 象山县| 黄梅县| 项城市| 京山县| 江北区| 临城县| 高尔夫| 怀柔区| 类乌齐县| 盈江县| 大足县| 光泽县| 江西省| 西乌珠穆沁旗| 绥化市| 巴彦淖尔市| 搜索| 五莲县| 开原市| 重庆市| 常熟市| 绥江县| 嘉义市| 璧山县| 临汾市| 太康县| 翼城县| 广德县| 崇阳县| 岑溪市| 铜川市| 新平| 景谷| 通渭县|