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.
文章图片
【spring|Spring里component-scan的工作原理】要获取更多Jerry的原创文章,请关注公众号"汪子熙":
文章图片
推荐阅读
- =======j2ee|spring用注解实现注入的@resource,@autowired,@inject区别
- jar|springboot项目打成jar包和war包,并部署(快速打包部署)
- 数据库|效率最高的Excel数据导入---(c#调用SSIS Package将数据库数据导入到Excel文件中【附源代码下载】)...
- java人生|35K 入职华为Java开发那天,我哭了(这 5 个月做的一切都值了)
- Java毕业设计项目实战篇|Java项目:在线嘿嘿网盘系统设计和实现(java+Springboot+ssm+mysql+maven)
- 微服务|微服务系列:服务发现与注册-----Eureka(面试突击!你想了解的Eureka都在这里.持续更新中......)
- java|ApplicationListener和SpringApplicationRunListener的联系
- Spring|SpringSecurity--自定义登录页面、注销登录配置
- 性能|性能工具之 Jmeter 通过 SpringBoot 工程启动
- 代码狂魔|Spring源码分析之IOC容器初始化流程