首先我们说一下自动配置的概念。
自动配置:遵循约定大约配置的原则,在boot程序启动后,起步依赖中的一些bean对象会自动注入到ioc容器
例子
程序引入spring-boot-starter-web 起步依赖,启动后,会自动往ioc容器中注入DispatcherServlet
项目结构:

Pom.xml中开始只有核心起步依赖,还没有spring-boot-starter-web 起步依赖。

再启动类中输出dispatcherServlet对象名。

运行启动类会报错,没有这个对象。

我们在pom.xml中添加spring-boot-starter-web 起步依赖:

再运行启动类,发现没有报错了,可以输出对象。

也就验证了程序引入spring-boot-starter-web 起步依赖 ,启动后,会自动往IOC容器中注入DispatcherServlet这个对象。
自动配置-源码分析

从**@SpringBootApplication注解** 入手,这个注解是组合注解,组合了下面三个注解,其中非常重要的是**@EnableAutoConfiguration注解**,即开启了自动配置。

@EnableAutoConfiguration注解也是组合注解,组合了下面两个注解,其中@Import注解这里导入了AutoConfigurationImportSelector 这个类 。它是ImportSelector接口的实现类,这个类里重写了selectImports方法,String[] selectImports(...)。

这个方法内部通过层层调用会读取一个配置文件,即External Libraries下的
org.springframework,boot.autoconfigure.AutoConfiguration.imports文件。

这个配置文件里面有一堆全类名,并且这些类都是自动配置类。其中的DispatcherServletAutoConfiguration就是完成DispatcherServlet这个bean对象的自动注入。

这个类长这样:

其中的**@AutoConfiguration** 表示这个类是自动配置类 ,**@Conditional0nClass(DispatcherServlet.class)**设置bean注册的条件。如果你的环境里有DispatcherServlet这个类,那么我们上图这个自动配置类就生效。如果没有,这个自动配置类就不生效。
而我们引入了spring-boot-starter-web 起步依赖就有这个类。如果没有这个类就证明没有引入web起步依赖。
所以说我们引入了spring-boot-starter-web 起步依赖,我们的spring boot就帮我们自动注入DispatcherServlet。
下图是自动注入的核心代码,它声明了一个方法,其返回值类型就是DispatcherServlet。还在这个方法上声明了一个Bean注解,把这个方法的返回值自动注入到IOC容器。

核心
如果觉得上面内容太多记不住,我们可以记住自动配置的核心是在这个.imports配置文件里。

在spring boot2.7以前使用的配置文件是Spring.factories

会从这个配置文件里读取一堆全类名。
而在spring boot2.7到3.0,同时兼容.imports和Spring.factories
在spring boot3.0以后就只支持.imports文件了。
通过上面内容我们可以知道,spring boot自动配置无非就是提供一个自动配置类,然后把这个类名写到指定的配置文件里面。
如果面试官问:说一说SpringBoot自动配置原理? 我们可以回答:
首先,在主启动类上添加了SpringBootApplication注解,这个注解组合了EnableAutoConfiguration注解。(EnableAutoConfiguration就是开启自动配置的意思)
然后,EnableAutoConfiguration注解又组合了Import注解,导入了AutoConfigurationImportSelector类。
然后呢,这个类实现了ImportSelector接口,实现了selectImports方法,这个方法经过层层调用,最终会读取META-INF 目录下的后缀名 为imorts的文件,当然了,boot2.7以前的版本,读取的是spring.factories文件。
这个文件读取到全类名了之后,会解析注册条件,也就是@Conditional及其衍生注解,把满足注册条件的Bean对象自动注入到I0C容器中。
希望这篇文章能够帮助到你^_^加油加油