SpringBoot自动装配的原理(参考文章)
首先在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}
)}
)
这里在自动装配方面起主要作用的是@EnableAutoConfiguration
点进去这话可以发现这个注解包含下面几个
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
可以看到import导入了一个类。
利用@Import注解,将所有符合自动装配条件的bean注入到IOC容器中
这个类AutoConfigurationImportSelector
很关键,进入
观察其selectImports
方法,这个方法执行完毕后,Spring会把这个方法返回的类的全限定名数组里的所有的类都注入到IOC容器中
这个类selectImports
里面调用了一个getAutoConfigurationEntry
方法,点进去
第一行if时会首先判断当前系统是否禁用了自动装配的功能,如果当前系统禁用了自动装配的功能则会返回如下这个空的数组,后续也就无法注入bean了,如果没有禁用自动装配则进入else分枝,第一步操作首先会去加载所有Spring预先定义的配置条件信息,这些配置信息在org.springframework.boot.autoconfigure
包下的META-INF/spring-autoconfigure-metadata.properties
文件中
这里就可以看到SpringBoot启动的时候就会去加载META-INF/spring.factories
里面配置的类。