SpringBoot的自动配置原理-创新互联

搭建SpringBoot环境非常简单,不需要各种配置文件,也不需要各种pom坐标
一个main入口方法一个@SpringBootApplication注解即可,为什么这样就可以呢
首先我们从Main方法开始

札达网站制作公司哪家好,找创新互联公司!从网页设计、网站建设、微信开发、APP开发、响应式网站设计等网站项目制作,到程序开发,运营维护。创新互联公司自2013年起到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联公司
@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);
    }
}

这个的@SpringBootApplication注解是关键,它是一个复合注解,让我们进去瞅瞅

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
excludeFilters = {@Filter(type = FilterType.CUSTOM,classes = {TypeExcludeFilter.class}), @Filter(type = FilterType.CUSTOM, classes = {AutoConfigurationExcludeFilter.class})})
public @interface SpringBootApplication {//...
}

我们发现@SpringBootApplication注解中有七个注解,但其中的三个注解起到了至关重要的作用分别是↓

@SpringBootConfiguration:我们点进去以后可以发现底层是Configuration注解,说白了就是表示这个spring boot启动类是一个配置类,最终要被注入到spring容器中。
@EnableAutoConfiguration:开启自动配置功能(后文详解)
@ComponentScan:这个注解,学过Spring的同学应该对它不会陌生,就是扫描注解,默认是扫描当前类下的package。将@Controller/@Service/@Component/@Repository等注解加载到IOC容器中

我们来说说@EnableAutoConfiguration这个注解,它也是哥复合注解,其中包含了两个比较重要的注解@AutoConfigurationPackage和@Import(AutoConfigurationImportSelector.class)注解
上源码↓

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
    Class[] exclude() default {};
    String[] excludeName() default {};
}

让我们先来看看@AutoConfigurationPackage注解它干了什么,进去看看

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({Registrar.class})
public @interface AutoConfigurationPackage {String[] basePackages() default {};

    Class[] basePackageClasses() default {};
}

没错它其中就是使用了一个@Import({Registrar.class})注解,其中 Registrar 类的作用是将启动类所在包下的所有子包的组件扫描注入到spring容器中
上源码↓

static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {Registrar() {}

        public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {AutoConfigurationPackages.register(registry, (String[])(new AutoConfigurationPackages.PackageImports(metadata)).getPackageNames().toArray(new String[0]));//没错就是这段
        }

        public SetdetermineImports(AnnotationMetadata metadata) {return Collections.singleton(new AutoConfigurationPackages.PackageImports(metadata));
        }
    }

OK我们回到@EnableAutoConfiguration上的 @Import({AutoConfigurationImportSelector.class})注解,看看它干了什么,这个@Import注解包含了一个AutoConfigurationImportSelector类,我们进入AutoConfigurationImportSelector的源码,看看有啥

public String[] selectImports(AnnotationMetadata annotationMetadata) {if (!this.isEnabled(annotationMetadata)) {return NO_IMPORTS;
        } else {AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(annotationMetadata);//开始调用getAutoConfigurationEntry
            return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
        }
    }

  protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {if (!this.isEnabled(annotationMetadata)) {return EMPTY_ENTRY;
        } else {AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
            Listconfigurations = this.getCandidateConfigurations(annotationMetadata, attributes);//得到很多的配置
            configurations = this.removeDuplicates(configurations);
            Setexclusions = this.getExclusions(annotationMetadata, attributes);
            this.checkExcludedClasses(configurations, exclusions);
            configurations.removeAll(exclusions);
            configurations = this.getConfigurationClassFilter().filter(configurations);
            this.fireAutoConfigurationImportEvents(configurations, exclusions);
            return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
        }
    }

然后我们进入getCandidateConfigurations方法看看干了什么

protected ListgetCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {//这里的this.getSpringFactoriesLoaderFactoryClass()就是筛选出以EnableAutoConfiguration为Key的信息
        Listconfigurations = new ArrayList(SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader()));
        ImportCandidates.load(AutoConfiguration.class, this.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;
    }

里面有一哥很重要的方法loadFactoryNames(),我们点进去看看
源代码如下↓

public static ListloadFactoryNames(ClassfactoryType, @Nullable ClassLoader classLoader) {ClassLoader classLoaderToUse = classLoader;
        if (classLoader == null) {classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
        }

        String factoryTypeName = factoryType.getName();
        return (List)loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList());
    }

    private static Map>loadSpringFactories(ClassLoader classLoader) {Map>result = (Map)cache.get(classLoader);
        if (result != null) {return result;
        } else {HashMap result = new HashMap();

            try {//这句很重要加载的就是这里,不同版本代码可能不太一样,我这是2.7.5
                Enumeration urls = classLoader.getResources("META-INF/spring.factories");

                while(urls.hasMoreElements()) {URL url = (URL)urls.nextElement();
                    UrlResource resource = new UrlResource(url);
                    Properties properties = PropertiesLoaderUtils.loadProperties(resource);
                    Iterator var6 = properties.entrySet().iterator();

                    while(var6.hasNext()) {Entryentry = (Entry)var6.next();
                        String factoryTypeName = ((String)entry.getKey()).trim();
                        String[] factoryImplementationNames = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
                        String[] var10 = factoryImplementationNames;
                        int var11 = factoryImplementationNames.length;

                        for(int var12 = 0; var12< var11; ++var12) {String factoryImplementationName = var10[var12];
                            ((List)result.computeIfAbsent(factoryTypeName, (key) ->{return new ArrayList();
                            })).add(factoryImplementationName.trim());
                        }
                    }
                }

                result.replaceAll((factoryType, implementations) ->{return (List)implementations.stream().distinct().collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
                });
                cache.put(classLoader, result);
                return result;
            } catch (IOException var14) {throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var14);
            }
        }
    }

总结一下就是
Spring启动的时候会扫描所有jar路径下的META-INF/spring.factories,将其文件包装成Properties对象
从Properties对象获取到key值为EnableAutoConfiguration的数据,然后添加到容器里
最后我们会默认加载113个默认的配置类

在这里插入图片描述

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


本文标题:SpringBoot的自动配置原理-创新互联
本文地址:http://scjbc.cn/article/dedpgi.html