自动装配 pom.xml
spring-boot-dependencies 核心依赖在父工程中
在写或者引入一些SpringBoot依赖的时候,不需要指定版本,因为有版本仓库
启动器 1 2 3 4 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter</artifactId > </dependency >
就是SpringBoot的启动场景: 比如spring-boot-starter-web就会帮我们导入web环境所有依赖
spring-boot将所有的场景功能,都编程一个个的启动器,需要什么功能,找对应的启动器
主程序 1 2 3 4 5 6 7 8 9 @SpringBootApplication public class Springboot01HelloworldApplication { public static void main (String[] args) { SpringApplication.run(Springboot01HelloworldApplication.class, args ); } }
注解 1 2 3 4 5 6 7 8 9 10 11 @SpringBootConfiguration : springboot的配置 @Configuration : spring配置类 @Component : 说明这也是一个spring的组件 @EnableAutoConfiguration : 自动配置 @AutoConfigurationPackage : 自动配置包 @Import({Registrar.class}) : 自动配置包注册 @AutoConfigurationImportSelector : 自动配置导入选择 List<String> configurations = this .getCandidateConfigurations(annotationMetadata, attributes);
获取候选的配置 1 2 3 4 5 protected List<String> getCandidateConfigurations (AnnotationMetadata metadata, AnnotationAttributes attributes) { List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this .getSpringFactoriesLoaderFactoryClass(), this .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; }
SpringFactoriesLoader.java 1 2 Properties properties = PropertiesLoaderUtils.loadProperties(resource);
原理分析
小结
springboot在启动的时候,从类路径下的/META-INF/spring.factories获取指定的值
将这些自动配置的类导入容器,自动配置就会生效,帮我们自动配置.
整合javaEE,解决方案和自动配置的东西都在spring-boot-autoconfigure-2.4.0.RELEASE.jar包
它会把所有的需要导入的组件,以类名的方式返回,这些组件就会被添加到容器中
容器中会存在非常多的xxxAutoConfiguration的文件,就是这些类给容器导入了这个场景需要的所有组件并自动配置,就是一个个的java config, @Configuration
以前我们需要手动配置的,springboot帮我们做了
结论 springboot所有的自动配置都是在启动的时候扫描并加载的: 所有的自动配置类都在spring.factories
,但是要导入对应的starter启动器,自动装配就会生效,然后就配置成功了