1:默认扫描启动类所在路径下所有的bean

2:可以在启动类中添加注解,手动指定扫描路径:

@componentscan(basepackages = {"com.xxx.service1.*","com.xxx.service2.**"})

补充:springboot 是如何通过 @springbootapplication 扫描项目中的 bean

原因

首先因为 xxxxxxxapplication 附带 @springbootapplication 注解,而 @springbootapplication 注解的层次如下:

springbootapplication
----@inherited
----@springbootconfiguration
--------@configuration
----@enableautoconfiguration
--------@inherited
--------@autoconfigurationpackage
------------@inherited
------------@import(autoconfigurationpackages.registrar.class)
--------@import(autoconfigurationimportselector.class)
----@componentscan
--------@repeatable(componentscans.class)

实现

可以看到 @springbootapplication 继承 @componentscan 与 @configuration 用处如下;

扫描方法开始流程:

主要观察黄色方块的方法,是具体扫描路径的地方,具体实现流程如下:

获取 file 目录下的所有以 class 为结尾的文件后,扫描工作就完成了, 剩下的就是 spring 判断是否要管理此类的逻辑(例如:该类是否存在 @component )

以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。如有错误或未考虑完全的地方,望不吝赐教。