Spring里component-scan的工作原理

Spring 专栏收录该内容
20 篇文章 0 订阅

In Spring configuration xml file, we can define a package for tag component-scan, which tells Spring framework to search all classes within this specified package, to look for those classes which are annotated with @Named or @Component.

I am very curious about how Spring framework achieves this scan, so I have made some debugging to figure it out.

In this blog How to find the exact location where bean configuration file is parsed in Spring framework I have already found the location where the xml configuration file is parsed by Spring framework, so I can directly set breakpoint in found source code.
Here the package to be scanned is parsed from xml file:

And the actual scan is performed in line 87:

Here all classes within the specified package and its children packages are extracted as resource, now I have 7 resources as candidates for scan which makes sense since I have totally 7 classes in the package:


The evaluation to check whether the class has qualified annotation is done in this method:

If the scanned class has at least one annotation ( the annotation written on class is stored in metsadataReader ) which resides in this.includeFilters, then it is considered as a candidate.

By inspecting content of this.includeFilters, we can know that Spring framework considers @Component and @Named as qualified annotation for automatic component scan logic.


Back to my example, since my bean class has @named annotated,

In the runtime, this annotation written in class source code is extracted via reflection, and checked against Spring framework pre-defined annotation set. Here below is how my bean class evaluated as candidate, since it has @Named annotation.


要获取更多Jerry的原创文章,请关注公众号"汪子熙":

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 博客之星2020 设计师:CY__ 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值