springboot自动装配原理

Source

pom.xml

父依赖

        其中它主要是依赖一个父项目,主要是管理项目的资源过滤及插件!

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

        点进去,发现还有一个父依赖

<!-- ... -->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.7.1</version>
  </parent>
<!-- ... -->

        再点进去,这里才是真正管理SpringBoot应用里面所有依赖版本的地方,SpringBoot的版本控制中心;

        以后我们导入依赖默认是不需要写版本;但是如果导入的包没有在依赖中管理着就需要手动配置版本了;

启动器spring-boot-starter

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

        springboot-boot-starter-xxx:就是spring-boot的场景启动器

        spring-boot-starter-web:帮我们导入了web模块正常运行所依赖的组件

        SpringBoot将所有的功能场景都抽取出来,做成一个个的starter (启动器),只需要在项目中引入这些starter即可,所有相关的依赖都会导入进来 , 我们要用什么功能就导入什么样的场景启动器即可 ;我们未来也可以自己自定义 starter;

        拓展:maven中的dependencyManagement

 

主启动类

默认的主启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

//程序的主入口
@SpringBootApplication
public class HelloworldApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloworldApplication.class, args);
    }

}

        @SpringBootApplication

        作用:标注在某个类上说明这个类是SpringBoot的主配置类 , SpringBoot就应该运行这个类的main方法来启动SpringBoot应用;

        进入这个注解:可以看到上面还有很多其他注解!

        @SpringBootConfiguration

        作用:springboot的配置类,标准在某个类上,表示这是一个springboot的配置类

        点进去这个注解,查看

//...
@Configuration
@Indexed
public @interface SpringBootConfiguration {
    //...
}
//...

        @Configuration

//...
@Component
public @interface Configuration {
    //...
}
//...

        这里的@Component,说明这个一个配置类,配置类就是对应spring的xml配置文件

里面的@Component这就说明启动类本身也是spring中的一个组件,负责启动应用

        

        @EnableAutoConfiguration开启自助配置功能

        以前我们需要自己配置的东西,现在springboot可以自助帮我们配置

        @EnableAutoConfiguration告诉springboot开启启动配置功能,这样自动配置才能生效

//...
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
    //...
}
//...

        @AutoConfigurationPackage自动配置包

//...
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {
    //...
}
//...

        @Import:spring底层注解@Import,给容器中导入一个组件

        Registrar.class作用:将主启动类的所在包及包下面所有子包里面的所有㢟扫描到spring容器

        @Import(AutoConfigurationImportSelector.class)给容器导入组件

        AutoConfigurationImportSelector:自助配置导入选择器

        那么它会导入哪些组件的选择器呢?我们点开一下源码:

        1.这个类中有一个这样的方法

// 获取候选配置
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
    List<String> configurations = new ArrayList<>(
        SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()));
    ImportCandidates.load(AutoConfiguration.class, getBeanClassLoader()).forEach(configurations::add);
    Assert.notEmpty(configurations,
                    "No auto configuration classes found in META-INF/spring.factories nor in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. If you "
                    + "are using a custom packaging, make sure that file is correct.");
    return configurations;
}

        

        注意这句(新版本看META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports)

No auto configuration classes found in META-INF/spring.factories 
nor 
in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. 
If you are using a custom packaging, make sure that file is correct.

        2.这个方法又调用了SpringFactoriesLoader的静态方法,我们进去loadFactoryNames方法    

public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
    ClassLoader classLoaderToUse = classLoader;
    if (classLoaderToUse == null) {
        classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
    }
    String factoryTypeName = factoryType.getName();
    //这里又调用了loadSpringFactories方法
    return loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList());
}

        3.我们继续点击查看loadSpringFactories方法

private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
    Map<String, List<String>> result = cache.get(classLoader);
    if (result != null) {
        return result;
    }

    result = new HashMap<>();
    try {
        Enumeration<URL> urls = classLoader.getResources(FACTORIES_RESOURCE_LOCATION);
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            UrlResource resource = new UrlResource(url);
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);
            for (Map.Entry<?, ?> entry : properties.entrySet()) {
                String factoryTypeName = ((String) entry.getKey()).trim();
                String[] factoryImplementationNames =
                    StringUtils.commaDelimitedListToStringArray((String) entry.getValue());
                for (String factoryImplementationName : factoryImplementationNames) {
                    result.computeIfAbsent(factoryTypeName, key -> new ArrayList<>())
                        .add(factoryImplementationName.trim());
                }
            }
        }

        // Replace all lists with unmodifiable lists containing unique elements
        result.replaceAll((factoryType, implementations) -> implementations.stream().distinct()
                          .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)));
        cache.put(classLoader, result);
    }
    catch (IOException ex) {
        throw new IllegalArgumentException("Unable to load factories from location [" +
                                           FACTORIES_RESOURCE_LOCATION + "]", ex);
    }
    return result;
}

        FACTORIES_RESOURCE_LOCATION

public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

        4.发现一个多次出现的文件:spring.factories,全局搜索它

        spring.factories (ps:最新的版本将被弃用)

        我们根据源头打开spring.factories , 看到了很多自动配置的文件;这就是自动配置根源所在!

         

        新版本看

 

        我们在上面的自动配置类随便找一个打开看看,比如 :WebMvcAutoConfiguration

 

        @AutoConfiguration

//...
@Configuration(proxyBeanMethods = false)
@AutoConfigureBefore
@AutoConfigureAfter
public @interface AutoConfiguration {
    //...
}
//...

        可以看到这些一个个的都是JavaConfig配置类,而且都注入了一些Bean,可以找一些自己认识的类,看着熟悉一下!

        所以,自动配置真正实现是从classpath中搜寻所有的META-INF/spring.factories配置文件 ,并将其中对应的 org.springframework.boot.autoconfigure. 包下的配置项,通过反射实例化为对应标注了 @Configuration的JavaConfig形式的IOC容器配置类 , 然后将这些都汇总成为一个实例并加载到IOC容器中。

结论

  1. springboot在启动的时候从类路径在的META-INF/spring.factories中获取@EnableAutoConfiguration指定的值(新版本从META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports中获取)

  2. 将这些值作为自动配置类导入容器,自助配置类就生效,帮我们进行自动配置工作

  3. 整个J2EE的整体解决方法和自动配置都在springboot-autoconfigure的jar包中

  4. 它会给容器中导入非常多的自动配置类(***AutoConfiguration),就是给容器中导入这个场景需要的所有组件,并配置好这些组件

  5. 有了自动配置类,免去了我们手动编写配置注入功能组件等的工作

SpringApplication

        我最初以为就是运行了一个main方法,没想到却开启了一个服务;

//...
@SpringBootApplication
public class Springboot01IdeaApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot01IdeaApplication.class, args);
    }

}

SpringApplication.run分析

        分析该方法主要分两部分,一部分是SpringApplication的实例化,二是run方法的执行;

SpringApplication

  这个类主要做了以下四件事情:

  1. 推断应用的类型是普通的项目还是web项目

  2. 查找并加载所有可用初始化器,设置到initializers属性中

  3. 找出所有的应用程序监听器,设置到listeners属性中

  4. 推断并设置main方法的定义类,找到运行的主类

        查看构造器:

//...
	public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
		this.resourceLoader = resourceLoader;
		Assert.notNull(primarySources, "PrimarySources must not be null");
		this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
		this.webApplicationType = WebApplicationType.deduceFromClasspath();
		this.bootstrapRegistryInitializers = new ArrayList<>(
				getSpringFactoriesInstances(BootstrapRegistryInitializer.class));
		setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
		setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
		this.mainApplicationClass = deduceMainApplicationClass();
	}
//...

run方法流程分析