面试题:请说一下SpringBoot自动装配原理?什么是自动装配?

面试当中,难免会遇到面试官问到这方面的问题,以我自己的理解简单记述一下此问题的回答。

什么是自动装配?

通过注解或一些简单的配置就能在 Spring Boot 的帮助下实现某块功能

原理过程如下:

第一步:@SpringBootApplication注解内部

三个重要的注解

@SpringBootConfiguration(实质就是一个@Configuration):允许在上下文中注册额外的 bean或导入其他配置类

@EnableAutoConfiguration:启用 SpringBoot 的自动配置机制,最核心的注解

@ComponentScan:扫描被@Component(@Service,@Controller)注解的 bean,注解默认会扫描启动类所在的包下所有的类 ,可以自定义不扫描某些 bean。

第二步:再进入@EnableAutoConfiguration注解

 自动装配核心功能的实现实际是通过@Import的 AutoConfigurationImportSelector类,它实现了selectImports方法,主要用于获取所有符合条件的类的全限定类名,这些类需要被加载到 IoC 容器中。 实现selectImports方法,调用getAutoConfigurationEntry获取需要自动装配的所有配置类。

 

 

得到:SpringBoot自动装配原理

The SelectImports class is imported into the EnableAutoConfiguration annotation. The selectImports method in this class will read the spring.factories file, and then get the value corresponding to EnableAutoConfiguration, which is the full class name of the default configuration class we automatically assemble. After getting this set, it is verified , remove duplicates, exclude auto-assembly, and execute listeners and other operations, and finally return a String array. This array is the configuration class collection that we will eventually auto-assemble. SpringBoot then loads the configuration and loads according to these data to complete the entire auto-assembly.

Guess you like

Origin blog.csdn.net/lzl770880/article/details/130099831