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 閱讀(200) 評論(0)  編輯  收藏 所屬分類: Spring
          主站蜘蛛池模板: 理塘县| 垦利县| 藁城市| 崇文区| 石阡县| 上蔡县| 鄂托克旗| 余干县| 安宁市| 琼海市| 金门县| 黔南| 克东县| 土默特左旗| 大悟县| 阿克苏市| 加查县| 大宁县| 玉林市| 富蕴县| 基隆市| 五河县| 隆德县| 平山县| 长武县| 荃湾区| 昂仁县| 灌阳县| 垫江县| 宜良县| 孟州市| 商城县| 岫岩| 灵武市| 福泉市| 武陟县| 萨迦县| 哈尔滨市| 荔波县| 五峰| 太仓市|