(参考的Spring version : 4.1.6.RELEASE)

我们通常会使用component-scan来进行bean的加载,但是它里面的实现机制却是一知半解。根据原码来理解一下,可能会更加清晰。

例如,我们通常会使用如下的配置:

application.xml:

<context:component-scan base-package="com.cn.kvn.service,com.cn.kvn.config,com.baidu">
<context:include-filter type="annotation" expression="com.alibaba.dubbo.config.annotation.Service" />
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

spring-servlet.xml:

<context:component-scan base-package="com.cn.kvn.controller" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

看了下面的解释,你就能大体知道这些配置具体是怎么控制和生效的了。

  • componentScan解析bean的入口为:ComponentScanBeanDefinitionParser#parse(Element element, ParserContext parserContext)
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
String basePackage = element.getAttribute(BASE_PACKAGE_ATTRIBUTE);
basePackage = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(basePackage);
String[] basePackages = StringUtils.tokenizeToStringArray(basePackage,
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); // Actually scan for bean definitions and register them.
ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element);
Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages);
registerComponents(parserContext.getReaderContext(), beanDefinitions, element); return null;
}

base-package属性告诉spring要扫描的包,use-default-filters="false"表示不要使用默认的过滤器

  • configureScanner会去配置scan时的使用的filter,其中use-default-filters属性是来控制是否要使用默认的过滤器的。

(默认的过滤器会去解析base-package下的含有@Component注解的类作为bean,其中@Repository, @Service, and @Controller都是@Component的子注解,故,默认的过滤器会将它们全部解析成bean)

原码中的英文注释:(ClassPathScanningCandidateComponentProvider#ClassPathScanningCandidateComponentProvider(boolean useDefaultFilters, Environment environment))

useDefaultFilters whether to register the default filters for the @Component, @Repository, @Service, and @Controller stereotype annotations
  • 用户自定义的include-filter和exclude-filter会在ComponentScanBeanDefinitionParser#parseTypeFilters(Element element, ClassPathBeanDefinitionScanner scanner, ParserContext parserContext)方法中被解析加载。
  • 在执行Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages);的时候,使用过滤器的顺序是,exclude-filter优于include-filter。

也就是说,如果同时定义了exclude-filter排除了某类(某个)bean,但是include-filter又将其包含了,则该bean不会被加载到spring容器。

ClassPathScanningCandidateComponentProvider.java
/**
* Determine whether the given class does not match any exclude filter
* and does match at least one include filter.
* @param metadataReader the ASM ClassReader for the class
* @return whether the class qualifies as a candidate component
*/
protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
for (TypeFilter tf : this.excludeFilters) {
if (tf.match(metadataReader, this.metadataReaderFactory)) {
return false;
}
}
for (TypeFilter tf : this.includeFilters) {
if (tf.match(metadataReader, this.metadataReaderFactory)) {
return isConditionMatch(metadataReader);
}
}
return false;
}

附:过滤规则设置

context:component-scan节点允许有两个子节点<context:include-filter>和<context:exclude-filter>。filter标签的type和表达式说明如下:

Filter Type Examples Expression Description include-filter为例
annotation org.example.SomeAnnotation 符合SomeAnnoation的target class

<context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>

表示扫描base-package下的类上加了Aspect注解的类,并注册到spring的bean容器

assignable org.example.SomeClass 指定class或interface的全名

<context:include-filter type="assignable" expression="com.test.scan.StuService"/>

指定扫描StuService类作为bean

aspectj org.example..*Service+ AspectJ語法  
regex org\.example\.Default.* Regelar Expression  
custom org.example.MyTypeFilter Spring3新增自訂Type,實作org.springframework.core.type.TypeFilter  

在我们的示例中,将filter的type设置成了正则表达式,regex,注意在正则里面.表示所有字符,而\.才表示真正的.字符。我们的正则表示以Dao或者Service结束的类。

我们也可以使用annotaion来限定,如下:

	<context:component-scan base-package="cn.outofmemory.spring" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/> 
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/> 
</context:component-scan>

这里我们指定的include-filter的type是annotation,expression则是注解类的全名。

另外context:conponent-scan节点还有<context:exclude-filter>可以用来指定要排除的类,其用法和include-filter一致。

spring component-scan filter的更多相关文章

  1. [Spring Boot] Use Component Scan to scan for Bean

    Component Scan is important concept when we want to create Bean. Currently we know what, for the cla ...

  2. 解决Spring Security自定义filter重复执行问题

    今天做项目的时候,发现每次拦截器日志都会打两遍,很纳闷,怀疑是Filter被执行了两遍.结果debug之后发现还真是!记录一下这个神奇的BUG! 问题描述 项目中使用的是Spring-security ...

  3. Spring框架之Filter应用

    在web.xml中进行配置,对所有的URL请求进行过滤,就像"击鼓传花"一样,链式处理. 配置分为两种A和B. 在web.xml中增加如下内容: <filter> &l ...

  4. not registered via @EnableConfigurationProperties or marked as Spring component

    利用@ConfigurationProperties(prefix = "")来绑定属性时报错: not registered via @EnableConfigurationPr ...

  5. Spring Cloud Zuul Filter 和熔断

    转一篇很不错的关于Spring Cloud Zuul 相关用法的文章,基本包含常用的一些场景,另外附上实际项目中的熔断.打印请求日志和登录验证的实例. 原文地址:https://www.cnblogs ...

  6. spring boot: 通过filter过滤器实现中文的简体繁体字符集转换(spring boot 2.3.1)

    一,为什么要使用filter来实现简繁体转换? 项目中有时会有同时支持简体和繁体两种字符集的要求, 或者搜索引擎有支持繁体输入字符的需求. 针对繁体字符的显示, 我们通常会在数据库和模板.文案配置中默 ...

  7. Spring Boot 使用 Filter

    Filter 是 JavaEE 中 Servlet 规范的一个组件,位于包javax.servlet 中,它可以在 HTTP 请求到达 Servlet 之前,被一个或多个Filter处理. 1. 编写 ...

  8. Spring @ Component 的作用

    1.@controller 控制器(注入服务) 2.@service 服务(注入dao) 3.@repository dao(实现dao访问) 4.@component (把普通pojo实例化到spr ...

  9. spring @Component

    使用 @Component <context:component-scan base-package="dao" />   虽 然我们可以通过@Autowired或@R ...

  10. spring security 4 filter 顺序及作用

    Spring Security 有两个作用:认证和授权 一.Srping security 4 filter 别名及顺序 spring security 4 标准filter别名和顺序,因为经常要用就 ...

随机推荐

  1. [转]如何让div中的内容垂直居中

    转自:http://blog.163.com/yan_1990/blog/static/197805107201211311515454/ 虽然Div布局已经基本上取代了表格布局,但表格布局和Div布 ...

  2. 用MySQL实现分页查询

    MySQL中实现分页查询语句: //定义分页需要的变量 int pageNow=2;//当前页 int pageSize=3;//指定每页显示3条记录 int pageCount=1;//该值是计算出 ...

  3. Java 设计模式泛谈&装饰者模式和单例模式

    设计模式(Design Pattern) 1.是一套被反复使用.多人知晓的,经过分类编目 的 代码设计经验总结.使用设计模式是为了可重用代码,让代码更容易维护以及扩展. 2.简单的讲:所谓模式就是得到 ...

  4. 局域网单机部署双tomcat内外网不能访问防火墙问题查出来

    tomcat部署的项目内网访问不了 win7  64 位 控制面板 - 安全 -防火墙-入站规则- 新建规则 选中“端口”按钮,点选“下一步”: 选择“TCP”按钮,在“特定本地端口”输入tomcat ...

  5. 利用ClouderaManager启动HBase时,出现 master.TableNamespaceManager: Namespace table not found. Creating...

    1.错误描述: 出现上述这个错误的原因是我之前已经安装了Cloudera Manager中的CDH,其中添加了所有的服务,当然也包含HBase.然后重新安装的时候,就会出现如下错误: Failed t ...

  6. android中图片的三级缓存cache策略(内存/文件/网络)

    实现图片缓存也不难,需要有相应的cache策略.这里我采用 内存-文件-网络 三层cache机制,其中内存缓存包括强引用缓存和软引用缓存(SoftReference),其实网络不算cache,这里姑且 ...

  7. HttpContext.Cache 详解

    提到HttpContext.Cache必然会想到Application,他们有什么共性和不同点呢,我们一一道来 相同点: 1.两者都是使用键值对来存储对象 2.两者都是应用程序同生命周期(在cache ...

  8. Java数据结构和算法之哈希表

    五.哈希表 一般的线性表.树中,记录在结构中的相对位置是随机的即和记录的关键字之间不存在确定的关系,在结构中查找记录时需进行一系列和关键字的比较.这一类查找方法建立在“比较”的基础上,查找的效率与比较 ...

  9. 《JavaScript模式》第5章 对象创建模式

    @by Ruth92(转载请注明出处) 第5章:对象创建模式 JavaScript 是一种简洁明了的语言,并没有其他语言中经常使用的一些特殊语法特征,如 命名空间.模块.包.私有属性 以及 静态成员 ...

  10. UrlRewrite伪静态

    1.首先添加URLRewriter.dll.ActionlessForm.dll加到bin文件夹中,添加引用 注:URLRewriter.dll实现伪静态  ActionlessForm.dll是分页 ...