@SpringBootApplication详解

一、@SpringBootApplication注解介绍

@SpringBootApplication这个注解是springboot启动类上的一个注解,是一个组合注解,也就是由其他注解组合起来,它的主要作用就是标记说明这个类是springboot的主配置类,springboot可以运行这个类里面的main()方法来启动程序

在这里插入图片描述

这个注解主要由三个子注解组成:

  • @SpringBootConfiguration
  • @EnableAutoConfiguration
  • @ComponentScan

 二、@SpringBootConfiguration介绍

这个注解包含了@Configuration,@Configuration里面又包含了一个@Component注解,也就是说,这个注解标注在哪个类上,就表示当前这个类是一个配置类,而配置类也是spring容器中的组件

在这里插入图片描述

在这里插入图片描述 

三、@ComponentScan介绍

包扫描注解:@ComponentScan 的作用就是根据定义的扫描路径,把符合扫描规则的类装配到spring容器中

四、@EnableAutoConfiguration介绍

这个注解是开启自动配置的功能,里面包含了两个注解

  • @AutoConfigurationPackage
  • @Import(AutoConfigurationImportSelector.class)

4.1  @AutoConfigurationPackage

它会自动扫描@SpringBootApplication注解所在类所在的包,并将该包及其子包下的所有组件加载到spring的容器中。

这个注解的作用说白了就是将主配置类(@SpringBootApplication标注的类)所在包以及子包里面的所有组件扫描并加载到spring的容器中,这也就是为什么我们在利用springboot进行开发的时候,无论是Controller还是Service的路径都是与主配置类同级或者次级的原因

4.2  @Import(AutoConfigurationImportSelector.class)

1.利用getAutoConfigurationEntry(annotationMetadata);给容器中批量导入一些组件

在这里插入图片描述
2.调用List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes)获取到所有需要导入到容器中的配置类

在这里插入图片描述
3.利用工厂加载 Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader);得到所有的组件

在这里插入图片描述
4.关键就在这个loadSpringFactories()方法里面,在这个方法里,它会查找所有在META-INF路径下的spring.factories文件,从META-INF/spring.factories文件中找到所有的对应配置类,然后将这些自动配置类加载到spring容器中。

在这里插入图片描述

在这里插入图片描述
默认扫描我们当前系统里面所有META-INF/spring.factories位置的文件
spring-boot-autoconfigure-2.3.4.RELEASE.jar包里面也有META-INF/spring.factories

虽然我们127个场景的所有自动配置启动的时候默认全部加载,但是xxxxAutoConfiguration按照条件装配规则(@Conditional),最终会按需配置。

AopAutoConfiguration类:

@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnProperty(
    prefix = "spring.aop",
    name = "auto",
    havingValue = "true",
    matchIfMissing = true
)
public class AopAutoConfiguration {
    public AopAutoConfiguration() {
    }
	...
}

猜你喜欢

转载自blog.csdn.net/weixin_55772633/article/details/131870673