Spring掃描通過注解定義的bean

1.引入context命名空間和context裝載路徑

xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd"

通過<context:component-scan base-package:"com.jack.*">
Spring容器就可以掃描com.jack包下的所有類,從類的注解信息獲取bean的定義信息。
如果希望掃描特定的類,而不是dao包下的所有類,可以使用resource-pattern指定需要過濾的特定的類,格式為resource-pattern:"*/.class",假如jack下有一個dao包
通過<context:component-scan base-package:"com.jack" resource-pattern:"dao/*.class">
就可以只掃描dao下的class
還可以通過context的子元素context:include-filtercontext:exclude-filter指定需要包含的和需要排除的文件,這兩個子元素可以包含多個。

<context:component-scan base-package="com.jack.*" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:exclude-filter type="aspectj" expression="org.springframework.stereotype.Repository"/>
    </context:component-scan>

<context:component-scan>先對context:exclude-filter中包含的元素進(jìn)行排除,然后掃描context:include-filter包含的文件,但是有一個默認(rèn)的屬性use-default-filters="true"會對所有的@Component,@Service,@Reposity,@Controller進(jìn)行掃描
use-default-filters="false"的作用是只加載context:include-filter包含的文件
對于type和expression的種類如下

image.png

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容