1. 前言
SpringBoot是目前软件中最主流的框架,无论是工作还是面试基本都有它的身影,SpringBoot主要解决了传统spring的重量级xml配置Bean,实现了自动装配;所以,我们也常在面试中被问到SpringBoot是如何实现自动装配。
本篇文章会从springboot源码进行自动装配的原理解析,并总结面试如何简洁的描述
2. 源码解析
我们以springboot 2.2.5.RELEASE版本进行解析
2.1 @SpringBootApplication源码解析
先看看springboot启动注解@SpringBootApplication
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
@AliasFor(annotation = EnableAutoConfiguration.class)
Class<?>[] exclude() default {};
@AliasFor(annotation = EnableAutoConfiguration.class)
String[] excludeName() default {};
@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
String[] scanBasePackages() default {};
@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
Class<?>[] scanBasePackageClasses() default {};
@AliasFor(annotation = Configuration.class)
boolean proxyBeanMethods() default true;
}
可以看出@SpringBootApplication是由三个注解组成的,@ComponentScan注解则是spring原生注解,其作用是扫描启动类所在的包以及子包所有Bean组件并注册到IOC容器中,两外两个我们再看看源码
@SpringBootConfiguration源码:
@EnableAutoConfiguration源码:
总结@SpringBootApplication注解由三个注解共同完成自动装配,各个注解作用如下
- @SpringBootConfiguration: 标记启动类为一个spring配置类
- @EnableAutoConfi