> 文档中心 > SpringBoot自动配置原理

SpringBoot自动配置原理

以@SpringBootApplication注解为起点总结自动配置原理
带红色序号的是表示有注释,写在下面了
在这里插入图片描述

①表示是一个springboot配置类
②将@SpringBootApplication包和子包下所有组件扫描到容器中(注册本地组件)

public static class Registrar{ public void registerBeanDefinitions(AnnotationMetadata metadata,BeanDefinitionRegistry registry){ AutoConfigurationPackages.register(registry,(String[])(new AutoConfigurationPackages.PackageImports(metadata)).getPackageNames().toArry(new String[0])); }}

④自动配置的导入选择器,决定导入哪些组件的选择器,将所有需要导入的组件以全类名的方式返回,这些组件就会被添加到容器中。会给容器中导入非常多的自动配置类(xxxAutoConfiguration),导入自动配置类,就会给容器中导入这个场景所需的所有组件并配置好这些组件

public string[] selectImports(AnnotationMetadata annotationMetadata){}

protected List getCandidateConfigurations(AnnotationMetadata metadata,AnnotationAttributes attributes)

List configutations= SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass (【return EnableAutoConfiguration.class】),getBeanClassLoader(【classLoader】)) loadFactoryNames(){ classLoader.getResources(FACTORIES_RESOURCE_LOCATION) 用类加载器获取一个资源 Properties properties=PropertiesLoaderUtils.loadProperties(new UrlResource(url)) 把获取的资源当作一个property文件 String factoryClassNames=properties.getProperty(factoryClassName) 从property文件中提取工程名字}

⑧String FACTORIES_RESOURCE_LOCATION="META_INF/spring.factories"从类路径下的META-INF/spring.factories中获取EnableAutoConfiguration的值:各种xxxAutoConfiguration,将这些值作为自动配置类导入到容器中,自动配置类就生效,帮我们进行自动配置工作,以前我们需要自己配置的东西,自动配置类就会帮我们配置。 J2EE的整体整合解决方案和自动配置都在spring-boot-autoconfigure-1.5.9.RELEASE.jar里面(各种xxxAutoConfiguration都在这里)