springboot自动配置原理-自己的学习过程中随便记录一下

120 阅读1分钟

springboot自动配置加载流程

  1. @SpringBootApplication内引入了@EnableAutoConfiguration
  2. @EnableAutoConfiguration内引入了@Import(AutoConfigurationImportSelector.class)
  3. @Import作用是将它引用的类注册到spring容器中,可以引用@Configuration注解的类
  4. ImportSelectorImportBeanDefinitionRegistrar的实现类,以及普通Java类

ImportSelector是一个接口,实现类需要重写它的selectImports方法,返回一个字符串数组,表示的一组希望交给spring容器管理的类的全限定类名

springboot提供的AutoConfigurationImportSelector这一实现中,将写在META-INF/spring.factories以及META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports这两个文件里的所有全限定类名作为selectImports方法的返回值

第三方库只需要将它们交给spring容器管理的类的全限定类名写到这两个文件中,即可实现自动配置

自定义spring-boot-starter

创建maven module

  1. component-spring-boot-starter

    starter用来管理依赖

  2. component-spring-boot-autoconfigure

    autoconfigure用来实现自动配置,创建相关bean并交给spring容器管理

  3. spring-autoconfigure-test

    只是用来测试效果

autoconfigure

在component-spring-boot-autoconfigure中创建类

// 假设希望这个类直接注册到spring容器中
public class Test {
  public void saySomething() {
    System.out.println("asdasd");
  }
}

在src/main/resources中创建文件:META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

文件中写入希望交给spring容器管理的类的全限定类名

com.example.component.Test

starter

在component-spring-boot-starter中引入component-spring-boot-autoconfigure(在本地机器上引入之前先对component-spring-boot-autoconfigure执行一下maven install)

测试

在测试模块中引入starter即可直接获得TestBean实例

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
  </dependency>

  <dependency>
    <groupId>com.example</groupId>
    <artifactId>component-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>
  </dependency>
</dependencies>
@SpringBootApplication
public class Main {
  public static void main(String[] args) {
    SpringApplication.run(Main.class, args);
  }

  @Bean
  public ApplicationRunner applicationRunner(Test testComponent) {
    return args -> {
      testComponent.saySomething(); // 控制台打印“test”
    };
  }
}