springboot自动装配大概原理
2023/4/26 1:22:27
本文主要是介绍springboot自动装配大概原理,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
自动装配:
pom.xml
- spring-boot-dependence:核心都依赖在父类工程中!
- 我们在写入或者引入springboot依赖的时候,不需要指定版,因为有这些仓库的版本
启动器:------spring boot的启动场景
- 比如spring-boot-starter-web,他就会帮我们导入web环境苏需要的依赖。
- springboot会将所有的功能场景,都变成一个个启动器。
- 我们使用什么功能,只需要找到对应的启动器(starter)就可以了
主程序:
//springbootApplication:标注这个类是一个springboot的应用,启动类下的所有资源被导入 @SpringBootApplication public class HuangApplication { public static void main(String[] args) { SpringApplication.run(HuangApplication.class, args); } }
注解:
@SpringBootConfiguration:springboot的配置 @Configuration: sring配置类 @@Component:说明这也是一个spring的组件 @@EnableAutoConfiguration: 自动配置 @AutoConfigurationPackage:自动配置 @Import(AutoConfigurationPackages.Registrar.class):导入选择器 @Import({AutoConfigurationImportSelector.class}):自动导入选择 //获取所有的配置 List<String>configurations=this.getCandidateConfigurations(annotationMetadata, attributes);
获取候选的配置:
protectedList<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { List<String> configurations = 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;
自动配置的核心:
META-INF/spring.factories
Properties properties = PropertiessloaderUtils.loadProperties(resource); 所有资源加载到配置类中!
结论:
springboot所有的自动配置都是在启动的时候扫描并加载:spring.factoriess所有的自动配置类都在这里面,但不一定全部启动,要判断条件是否成立,只要导入对应的start,就有对应的启动器了,有了启动器,我们的自动装配就会生效,然后配置就会成功。
大概步骤:
1.
spring boot在启动的时候,从路径下/META-INF/spring.factories获取指定的值。
2.
将这些自动配置的类导入容器,自动配置就会生效,进行自动配置。
3.
以前我们需要自动配置的东西,现在都在springboot帮我们做。
4.
整合javaEE,解决方案和自动装配的东西都在spring-boot-autofigure- 2.7.11.RELEASE.JAR这个包下面
5.
他会把所有需要导入的组件,以类的方式返回,这些组件就会被添加到容器。
6.
容器中也会存在非常多的xxxAutoConfiguration的文件(@bean),就是这些类给容器中导入了这个场景需要的所有组件,并自动配置。
代码表示(自动配置原理)
这篇关于springboot自动装配大概原理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?