spring boot插件开发实战和原理
本文转载自spring boot插件开发实战和原理
实战:编写spring boot插件
为什么要编写boot插件
因为我们在开发的时候需要提供一些共同的功能,所以我们编写个共同的jar包。开发人员在使用jar包的时候不用考虑jar包的内容,直接使用具体的功能即可,但是可能由于包路径的不同,你所编写的bean没有被初始化到spring容器中。不应该让开发人员去扫描你的包路径去初始化bean。所以我们要自己动手去把bean初始化到bean容器中,这也是spring扩展能力的由来(spriing.factories)
实战
编写插件代码,编写配置类(例如:DemoAutoConfig),在其中定义你需要的bean 在resources下创建META-INF/spring.factories 编写spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.demo.DemoAutoConfig
spring.factories 常用配置接口
org.springframework.boot.SpringApplicationRunListener
SpringApplicationRunListener来监听Spring Boot的启动流程,并且在各个流程中处理自己的逻辑。在应用启动时,在Spring容器初始化的各个阶段回调对应的方法。
org.springframework.context.ApplicationContextInitializer
ApplicationContextInitializer是在springboot启动过程上下文 ConfigurableApplicationContext刷新方法前(refresh)调用,对ConfigurableApplicationContext的实例做进一步的设置或者处理。
org.springframework.boot.autoconfigure.EnableAutoConfiguration
定义系统自动装配的类。
org.springframework.boot.env.EnvironmentPostProcessor
配置环境的集中管理。比如扩展去做排除加载系统默认的哪些配置类,方便自定义扩展。
org.springframework.boot.autoconfigure.AutoConfigurationImportFilter
自动装配类排除
spring factories 原理
获取配置流程
在启动类注解@SpringBootApplication中可以看到引用了@EnableAutoConfiguration。 其中@Import(AutoConfigurationImportSelector.class)
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return NO_IMPORTS;
}
AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
.loadMetadata(this.beanClassLoader);
AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(autoConfigurationMetadata,
annotationMetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
其中getAutoConfigurationEntry方法
protected AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata,
AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return EMPTY_ENTRY;
}
AnnotationAttributes attributes = getAttributes(annotationMetadata);
List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
configurations = removeDuplicates(configurations);
Set<String> exclusions = getExclusions(annotationMetadata, attributes);
checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = filter(configurations, autoConfigurationMetadata);
fireAutoConfigurationImportEvents(configurations, exclusions);
return new AutoConfigurationEntry(configurations, exclusions);
}
其中getCandidateConfigurations
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;
}
调用了SpringFactoriesLoader.loadFactoryNames
public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
String factoryTypeName = factoryType.getName();
return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
}
loadSpringFactories方法
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
private static final Map<ClassLoader, MultiValueMap<String, String>> cache = new ConcurrentReferenceHashMap<>();
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
MultiValueMap<String, String> result = cache.get(classLoader);
if (result != null) {
return result;
}
try {
Enumeration<URL> urls = (classLoader != null ?
classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
result = new LinkedMultiValueMap<>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
UrlResource resource = new UrlResource(url);
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
for (Map.Entry<?, ?> entry : properties.entrySet()) {
String factoryTypeName = ((String) entry.getKey()).trim();
for (String factoryImplementationName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
result.add(factoryTypeName, factoryImplementationName.trim());
}
}
}
cache.put(classLoader, result);
return result;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load factories from location [" +
FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}
加载配置流程
在main方法启动的时候我们会调用SpringApplication.run方法 run方法中调用了getSpringFactoriesInstances 调用createSpringFactoriesInstances
private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes,
ClassLoader classLoader, Object[] args, Set<String> names) {
List<T> instances = new ArrayList<>(names.size());
for (String name : names) {
try {
Class<?> instanceClass = ClassUtils.forName(name, classLoader);
Assert.isAssignable(type, instanceClass);
Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes);
T instance = (T) BeanUtils.instantiateClass(constructor, args);
instances.add(instance);
}
catch (Throwable ex) {
throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, ex);
}
}
return instances;
}
总结
这是一种类似插件的设计方式,只要引入对应的jar包,就会扫描到jar里的spring.factories,对应的实现类也就会被实例化。
spring boot插件开发实战和原理的更多相关文章
- Spring Boot 文件上传原理
首先我们要知道什么是Spring Boot,这里简单说一下,Spring Boot可以看作是一个框架中的框架--->集成了各种框架,像security.jpa.data.cloud等等,它无须关 ...
- Spring Boot 项目实战(五)集成 Dubbo
一.前言 上篇介绍了 Redis 的集成过程,可用于解决热点数据访问的性能问题.随着业务复杂度的提高,单体应用越来越庞大,就好比一个类的代码行数越来越多,分而治之,切成多个类应该是更好的解决方法,所以 ...
- “Spring Boot+Marklogic实战应用(1)”
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议.本文链接:http://www.blbk.info Spring Boot+Marklogic应用 摘要: 在前一节的介绍,相信 ...
- Spring Boot GraphQL 实战 02_增删改查和自定义标量
hello,大叫好,我是小黑,又和大家见面啦~ 今天我们来继续学习 Spring Boot GraphQL 实战,我们使用的框架是 https://github.com/graphql-java-ki ...
- Spring Boot GraphQL 实战 03_分页、全局异常处理和异步加载
hello,大家好,我是小黑,又和大家见面啦~ 今天我们来继续学习 Spring Boot GraphQL 实战,我们使用的框架是 https://github.com/graphql-java-ki ...
- Spring Boot的自动配置原理及启动流程源码分析
概述 Spring Boot 应用目前应该是 Java 中用得最多的框架了吧.其中 Spring Boot 最具特点之一就是自动配置,基于Spring Boot 的自动配置,我们可以很快集成某个模块, ...
- 【建议收藏】缺少 Vue3 和 Spring Boot 的实战项目经验?我这儿有啊!
缺少 Vue3 和 Spring Boot 的实战项目经验?缺少学习项目和练手项目?我这儿有啊! 从 2019 年到 2021 年,空闲时间里陆陆续续做了一些开源项目,推荐给大家啊!记得点赞和收藏噢! ...
- Spring Boot 2 实战:利用Redis的Geo功能实现查找附近的位置
1. 前言 老板突然要上线一个需求,获取当前位置方圆一公里的业务代理点.明天上线!当接到这个需求的时候我差点吐血,这时间也太紧张了.赶紧去查相关的技术选型.经过一番折腾,终于在晚上十点完成了这个需求. ...
- Spring Boot 自动配置的原理、核心注解以及利用自动配置实现了自定义 Starter 组件
本章内容 自定义属性快速入门 外化配置 自动配置 自定义创建 Starter 组件 摘录:读书是读完这些文字还要好好用心去想想,写书也一样,做任何事也一样 图 2 第二章目录结构图 第 2 章 Spr ...
随机推荐
- MySql命令,吐血整理的Mysql,实话,真的吐血
MySql命令,吐血整理的Mysql,实话,真的吐血 1.基本操作 2.数据库操作 3.表的操作 4.数据操作 5.字符集编码 6.数据类型(列类型) 7.列属性(列约束) 8.建表规范 9.SELE ...
- Hive 使用总结
1 带分区列的表更改列类型 常见的一个场景是Hive里面一个带分区的表,原来是int类型的字段,后来发现数据超过了int的最大值,要改成bigint.或者是bigint要改string或decimal ...
- 一周精彩内容分享(第 1 期):"世纪逼空大战"
这里记录过去一周,我看到的值得分享的东西. 一方面是整理记录一下自己一周的学习,另一方面也是期待自己有更多的输出,有更多的价值. 周刊开源(Github:wmyskxz/weekly),欢迎提交 is ...
- bootstrap实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Relatives POJ - 2407 欧拉函数
题意: 给你一个正整数n,问你在区间[1,n)中有多少数与n互质 题解: 1既不是合数也不是质数(1不是素数) 互质是公约数只有1的两个整数,叫做互质整数.公约数只有1的两个自然数,叫做互质自然数 所 ...
- JavaScript函数console、this关键字
console.dir()打印出来的东西不加任何操作 console.log()打印出来东西实现进行了操作,打印出来的东西可能不是原型 具体对象的类型可以在"_proto_"中看, ...
- CodeCraft-20 (Div. 2) B. String Modification (字符串,规律)
题意:有一个长度为\(n\)的字符串,你可以选取一个值\(k(1\le k \le n)\),然后遍历字符串,每次将区间长度为\(k\)的字符串反转,求反转后字典序最小的字符串,并输出\(k\)的值. ...
- 13. 从0学ARM-Cortex-A9 RTC裸机程序编写
一.RTC RTC(Real-Time Clock) 实时时钟. RTC是集成电路,通常称为时钟芯片.在一个嵌入式系统中,通常采用RTC来提供可靠的系统时间,包括时分秒和年月日等,而且要求在系统处于关 ...
- k8s-2-集成apollo配置中心
主题: 在k8s中集成Apollo配置中心 架构图 一.配置中心概述 配置的几种方式 本课讲得是基于配置中心数据库实现 配置管理的现状 常见的配置中心 主讲:k8s configmap,apollo ...
- EDA : quartus2 17.1lite + modelsim +verilog 使用流程
首先 然后填充好自己写的代码 之后save as 存到自己的文件夹 会自动弹出 配置 Assignments settings 之后第一次编译 成功后processing star ...