Springboot自动装配原理

@SpringBootApplication // 当前启动类是配置类
 -->
  @SpringBootConfiguration // springboot的启动类其实也就是作为spring的一个bean注入到spring容器中
  @ComponentScan // 定义扫描的路径从中找出标识了需要装配的类自动装配到spring的bean容器中
  @EnableAutoConfiguration --> // 开启自动装配的核心注解 作用是获取配置类 扫描并注入IOC容器中进行管理
    @Import(AutoConfigurationImportSelector.class)-->
       protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
            AnnotationAttributes attributes) {
        List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
                getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
        Assert.notEmpty(configurations,
                "No auto configuration classes found in META-INF/spring.factories. If you "
                        + "are using a custom packaging, make sure that file is correct.");
        return configurations;
    }

META-INF/spring.factories:

# Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\
org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener

# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.autoconfigure.BackgroundPreinitializer

# Auto Configuration Import Listeners
org.springframework.boot.autoconfigure.AutoConfigurationImportListener=\
org.springframework.boot.autoconfigure.condition.ConditionEvaluationReportAutoConfigurationImportListener

# Auto Configuration Import Filters
org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
org.springframework.boot.autoconfigure.condition.OnBeanCondition,\
org.springframework.boot.autoconfigure.condition.OnClassCondition,\
org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\

Spring Boot在启动的时候就是从类路径下的META-INF/spring.factories中获取需要自动装配的类 (一些配置组件),找到这些类(XXXAutoConfiguration),通过SpringFactoriesLoader机制创建对应的bean,注入到容器中,完成了自动注入spring容器,本来需要在spring的xml配置文件中去配置bean的操作就免去了 ,也就是springboot完成了自动装配。

最后修改:2020 年 12 月 01 日 06 : 48 PM