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中包含的元素进行排除,然后扫描context:include-filter包含的文件,但是有一个默认的属性use-default-filters="true"会对所有的@Component,@Service,@Reposity,@Controller进行扫描
use-default-filters="false"的作用是只加载context:include-filter包含的文件
对于type和expression的种类如下

image.png

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。