@SpringBootApplication
public class HelloSpringBoot{
public static void main(String[] args) {
SpringApplication.run(HelloSpringBoot.class, args);
}
}
1 内部原理 ⭐️
(1) 将HelloSpringBoot.class
作为参数传入SpringApplication#run
方法;
(2) 创建"BeanDefinition加载器"对象
在容器准备阶段prepareContext(..)
, 将HelloSpringBoot.class
和 之前创建的AnnotationConfigEmbeddedWebApplicationContext实例
作为参数,创建 BeanDefinitionLoader实例
在 “BeanDefinitionLoader” 的构造方法中创建一个 "Reader"
对象 最终状态图如下
(3) "BeanDefinitionLoader"中的 “Reader” 读取启动类,并使用工具类将其注册进Spring容器
“BeanDefinitionLoader” 使用工具类 [注1]会递归判断该类是否为有@Component注解 ,有则 “BeanDefinition加载器” 的 “Reader” 使用工具类 [注2]将其注册进容器
因为启动类上加了 @SpringBootApplication
注解, 该注解派生自@Configuration ,所以启动类就是个配置类.⭐️
[注1] 注解工具类:
AnnotationUtils.findAnnotation(启动类.class, Component.class)
[注2] 注册工具类:BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry)
画张图总结一下
(4) 解析配置类的@ComponentScan注解
实际上 @SpringBootApplication
注解还派生了@ComponentScan注解
在Spring调用配置后置处理器解析配置类时, 会从容器中找出所有的配置类, 然后解析这些配置类 , 其中一道工序就是处理配置类的@ComponentScan注解 , 如果该注解没有设置basePackage
属性值, 则将该配置类所在的包作为扫描包 .
2 源码debug查看
前置知识:
o.s.beans.factory.support.DefaultListableBeanFactory#registerBeanDefinition方法是注册BeanDefinition的地方.
在方法的第一行打上断点,并在断点中加入条件判断 beanName.equals("springBootWebAppMain")
(springBootWebAppMain 为启动类的类名首字母小写) , 启动程序, 调用栈如下:
registerBeanDefinition:796, DefaultListableBeanFactory (o.s.beans.factory.support)
registerBeanDefinition:320, GenericApplicationContext (o.s.context.support)
registerBeanDefinition:149, BeanDefinitionReaderUtils (o.s.beans.factory.support)
registerBean:192, AnnotatedBeanDefinitionReader (o.s.context.annotation)
registerBean:142, AnnotatedBeanDefinitionReader (o.s.context.annotation)
register:131, AnnotatedBeanDefinitionReader (o.s.context.annotation)
load:159, BeanDefinitionLoader (o.s.boot)
load:135, BeanDefinitionLoader (o.s.boot)
load:127, BeanDefinitionLoader (o.s.boot)
load:635, SpringApplication (o.s.boot)
prepareContext:355, SpringApplication (o.s.boot)
run:301, SpringApplication (o.s.boot)
main:28, PropertyTestMainSpringApplication (com.yh.stu.springboot.property)