以前写过starter的原理,但是对于最重要的点 自动装配给略过去了。拉个会对齐一下 ·
引入了starter以后spring是将bean加载到容器中了,spring会采用spi技术查询meta/spring.factories底下的全路径配置文件,这个文件就是对应的配置文件(@Configuration)。里面有一个bean,会把这个bean自动加载到容器中,实现这个是由EnableAutoConfiguration这个注解实现的,它包含在SpringBootApplication这个注解中,另外两个是
@SpringBootConfiguration 配置类(我们为什么要将一个类标记为配置类??通过将类标记为配置类,Spring 容器会自动扫描并解析其中的注解,根据配置类的定义和相关注解进行相应的处理)
@ComponentScan 扫描
spring有哪些bean容器
Spring Framework 中的 bean 容器有多种,其中最常见的是:
BeanFactory:是 Spring 框架中最基本的容器,提供了基本的 DI 功能。
ApplicationContext:是 BeanFactory 的子接口,提供了更多的企业级功能,如事件发布、国际化等。
AnnotationConfigApplicationContext:基于注解配置的应用上下文,通过注解来声明 bean。
ClassPathXmlApplicationContext:基于 XML 配置文件的应用上下文,通过 XML 来声明 bean。
FileSystemXmlApplicationContext:基于文件系统路径的应用上下文,同样也是通过 XML 配置文件声明 bean。
EnableAutoConfiguration详解
源码是由这两个实现的
@AutoConfigurationPackage
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {
/**
* Base packages that should be registered with {@link AutoConfigurationPackages}.
* <p>
* Use {@link #basePackageClasses} for a type-safe alternative to String-based package
* names.
* @return the back package names
* @since 2.3.0
*/
String[] basePackages() default {};
/**
* Type-safe alternative to {@link #basePackages} for specifying the packages to be
* registered with {@link AutoConfigurationPackages}.
* <p>
* Consider creating a special no-op marker class or interface in each package that
* serves no purpose other than being referenced by this attribute.
* @return the base package classes
* @since 2.3.0
*/
Class<?>[] basePackageClasses() default {};
}
@Import(AutoConfigurationImportSelector.class)
这一步是获得了一个map
key是org.springframework.boot.autoconfigure.EnableAutoConfiguration
value是配置的全路径
总结
1.自动装配是由EnableAutoConfiguration实现的
2.EnableAutoConfiguration底下有两个实现
一个是@AutoConfigurationPackage 这个类将当前spring工程的bean加载到容器中
另一个是@Import(AutoConfigurationImportSelector.class) 它有一个selectImports方法,主要是将meta/spring.factories里面的配置读取出来,然后返回一个map,key是org.springframework.boot.autoconfigure.EnableAutoConfiguration
value是配置的全路径,这样就将所有的配置类导入了。
3.AutoConfigurationImportSelector类通过实现DeferredImportSelector延迟导入接口,在容器初始化的过程中在完成以上动作;