Java SPI与SpringBoot 自动配置

Java SPI设计思想

1、使用约定的配置文件

2、谁提供jar包,也要负责提供配置文件

3、使用ClassLoader的getResource和getResources方法,来读取classpath中的配置文件

 

SpringBoot自动配置核心实现

1、使用约定的配置文件:

1.1 文件路径是META-INF/spring.factories

1.2 文件内容是“key=value1,value2...valueN”的格式

其中key是 EnableAutoConfiguration的类名,value是自动配置类的类名

2、提供自动配置类的jar包,也同时提供配置文件MATA-INF/spring.factories

3、和SPI一样:使用ClassLoader的getResources和getResources方法来读取classPath中的配置文件。

 

SpringBoot自动配置的核心流程:

1、SpringBoot应用程序启动->通过Spring Factories机制加载配置文件->筛选出所有自动配置类->将这些类注入到SpringIOC容器中

机制:通过ClassLoader去获取classpath中的配置文件META-INF/spring.factories。 springFacotries是Spring框架内置的,是spring框架对外扩展的入口,很多地方都要用到。

筛选:在所有配置文件中META-INF/spring.facotries中,筛选出以EnableAutoConfiguration为key的配置值。

 

SpringBoot自动配置

启动流程伪代码:

1、创建一个ApplicationContext实例,即我们的IOC容器

ApplicationContext context=createApplicationContext();

2、将主类 mainClass 注册到IOC容器中

loadSourceClass(context,mainclass)

3、递归加载处理所有配置类

processConfigurationClasses(context)

4、实例化所有的单例bean(Singleton Bean),"依赖注入”和“自动装配”

instantiateSingletonBeans(context)

5、如果是web应用则启动web服务器(tomcat)

startWebServer(context);

 

 

1.1 首先从IOC容器中取出当前存在的源配置类

2.2 创建一个配置类解析器,然后递归加载并处理应用中的所有配置类

3.1 向IOC容器中注册@Bean方法对应的BeanDefinition

3.2 向IOC容器中注册ImportBeanDefinitionRegister导入BeanDefinition

 

加载配置类的流程:

1、处理@ComponentScan:根据@ComponentScan扫描指定的package,得到一系列配置类

2、处理注解@Import:根据注解Import,得到一系列被导入的配置类

3、处理@Bean方法

4、处理@Import导入的ImportBeanDefinitionRegistar

5、加入到一个全局的配置类集合中

notice:源配置类,通过ComponentScan、@Scan、@Import依次递归遍历注册bean到IOC容器中

 

 

导入ImportSelector选择器实现自动配置

@SpringBootApplication->@EnableAutoConfiguration->@Import(AutoConfigurationImportSelector.class)->AutoConfigurationImportSelect继承了ImportSelector接口->getAutoConfigurationEntry()->

去Spring.factories下面去加载配置类

 

 

  

posted @ 2022-08-30 11:07  雷雷提  阅读(329)  评论(0编辑  收藏  举报