【Spring Boot 源码学习】OnWebApplicationCondition 详解

news/2024/9/20 7:21:48

Spring Boot 源码学习系列

在这里插入图片描述

OnWebApplicationCondition 详解

  • 引言
  • 往期内容
  • 主要内容
    • 1. getOutcomes 方法
    • 2. getMatchOutcome 方法
    • 3. isWebApplication 方法
      • 3.1 isServletWebApplication 方法
      • 3.2 isReactiveWebApplication 方法
      • 3.3 isAnyWebApplication 方法
  • 总结

引言

上篇博文带大家从 Spring Boot 源码深入详解了 OnBeanCondition,那本篇也同样从源码入手,带大家深入了解 OnWebApplicationCondition 的过滤匹配实现。

往期内容

在开始本篇的内容介绍之前,我们先来看看往期的系列文章【有需要的朋友,欢迎关注系列专栏】:

Spring Boot 源码学习
Spring Boot 项目介绍
Spring Boot 核心运行原理介绍
【Spring Boot 源码学习】@EnableAutoConfiguration 注解
【Spring Boot 源码学习】@SpringBootApplication 注解
【Spring Boot 源码学习】走近 AutoConfigurationImportSelector
【Spring Boot 源码学习】自动装配流程源码解析(上)
【Spring Boot 源码学习】自动装配流程源码解析(下)
【Spring Boot 源码学习】深入 FilteringSpringBootCondition
【Spring Boot 源码学习】OnClassCondition 详解
【Spring Boot 源码学习】OnBeanCondition 详解

主要内容

本篇我们重点详解 OnWebApplicationCondition 的实现,参见如下:

在这里插入图片描述

1. getOutcomes 方法

鉴于前面博文的了解,我们知道 OnWebApplicationCondition 也是 FilteringSpringBootCondition 的子类,所以这里同样也是从 getOutcomes 方法源码来分析【Spring Boot 2.7.9】:

@Order(Ordered.HIGHEST_PRECEDENCE + 20)
class OnWebApplicationCondition extends FilteringSpringBootCondition {

	// ...

	@Override
	protected ConditionOutcome[] getOutcomes(String[] autoConfigurationClasses,
			AutoConfigurationMetadata autoConfigurationMetadata) {
		ConditionOutcome[] outcomes = new ConditionOutcome[autoConfigurationClasses.length];
		for (int i = 0; i < outcomes.length; i++) {
			String autoConfigurationClass = autoConfigurationClasses[i];
			if (autoConfigurationClass != null) {
				outcomes[i] = getOutcome(
						autoConfigurationMetadata.get(autoConfigurationClass, "ConditionalOnWebApplication"));
			}
		}
		return outcomes;
	}
	// ...
}

上述逻辑很容易理解,遍历自动配置数组 autoConfigurationClasses ,循环如下:

  • 首先,从 autoConfigurationClasses 中获取自动配置数据 autoConfigurationClass

  • 然后,调用 AutoConfigurationMetadata 接口的 get(String className, String key) 方法来获取与 autoConfigurationClass 关联的名为 "ConditionalOnWebApplication" 的条件属性值【即应用类型枚举值】;

    应用类型枚举可以查看 @ConditionalOnWebApplication 注解获取,如下所示:

    在这里插入图片描述

  • 最后,调用 getOutcome 方法,并传入上述获取的应用类型枚举值 type
    在这里插入图片描述

    • 如果 typeSERVLET, 则判断 org.springframework.web.context.support.GenericWebApplicationContext 是否存在;
      如果不存在,则返回一个未满足过滤匹配条件的 ConditionOutcome 对象【其中包含 did not find servlet web application classes 的信息 】。
    • 如果 typeREACTIVE,则判断 org.springframework.web.reactive.HandlerResult 是否存在;
      如果不存在,则返回一个未满足过滤匹配条件的 ConditionOutcome 对象【其中包含 did not find reactive web application classes 的信息 】。
    • 如果 org.springframework.web.context.support.GenericWebApplicationContext 不存在且 org.springframework.web.reactive.HandlerResult 也不存在,则返回一个未满足过滤匹配条件的 ConditionOutcome 对象【其中包含 did not find reactive or servlet web application classes 的信息 】。
    • 如果都存在,则直接返回 null

2. getMatchOutcome 方法

OnClassCondition 一样,OnWebApplicationCondition 同样实现了 FilteringSpringBootCondition 的父类 SpringBootCondition 中的抽象方法 getMatchOutcome 方法。

有关 SpringBootCondition 的介绍,这里不赘述了,请查看笔者的 【Spring Boot 源码学习】OnClassCondition 详解。

那么,我们进入 getMatchOutcome 方法中查看如下源码【Spring Boot 2.7.9】:

@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
	boolean required = metadata.isAnnotated(ConditionalOnWebApplication.class.getName());
	ConditionOutcome outcome = isWebApplication(context, metadata, required);
	if (required && !outcome.isMatch()) {
		return ConditionOutcome.noMatch(outcome.getConditionMessage());
	}
	if (!required && outcome.isMatch()) {
		return ConditionOutcome.noMatch(outcome.getConditionMessage());
	}
	return ConditionOutcome.match(outcome.getConditionMessage());
}

我们来分析一下相关逻辑:

  • 首先,通过调用 AnnotatedTypeMetadata 接口的 isAnnotated 方法,判断元数据中是否存在 @ConditionalOnWebApplication 注解【当应用程序为 Web 应用程序时,该条件注解用来匹配】。如果返回 true,表示元数据中存在指定注解;否则,返回 false

  • 然后,调用 isWebApplication 方法来获取条件匹配结果 outcome【有关内容查看 第 3 小节】;

  • 如果 requiredtrue【即存在 @ConditionalOnWebApplication 注解】,并且 条件结果不匹配,则返回一个新的 ConditionOutcome 对象,标记为不匹配,并带有原始的消息。

  • 如果 requiredfalse【即不存在 @ConditionalOnWebApplication 注解】,并且 条件结果匹配,则同样返回一个新的 ConditionOutcome 对象,标记为不匹配,并带有原始的消息。

  • 最后,上述两个条件判断都不满足,则将返回一个匹配的 ConditionOutcome 对象,并带有原始的消息。

3. isWebApplication 方法

下面,我们进入 isWebApplication 方法中:

private ConditionOutcome isWebApplication(ConditionContext context, AnnotatedTypeMetadata metadata,
			boolean required) {
	switch (deduceType(metadata)) {
		case SERVLET:
			return isServletWebApplication(context);
		case REACTIVE:
			return isReactiveWebApplication(context);
		default:
			return isAnyWebApplication(context, required);
	}
}

上述的逻辑也很简单:

  • 首先,通过 deduceType 方法获取可获取的应用类型;查看其源码可知,如果存在 @ConditionalOnWebApplication 注解,则获取其对应的 type 属性;否则默认返回 Type.ANY【即任何 Web 应用程序都将匹配】。

    private Type deduceType(AnnotatedTypeMetadata metadata) {
    	Map<String, Object> attributes = metadata.getAnnotationAttributes(ConditionalOnWebApplication.class.getName());
    	if (attributes != null) {
    		return (Type) attributes.get("type");
    	}
    	return Type.ANY;
    }
    
  • 如果是 Type.SERVLET,则调用 isServletWebApplication 方法返回条件匹配结果。

  • 如果是 Type.REACTIVE,则调用 isReactiveWebApplication 方法返回条件匹配结果。

  • 如果不是上述两个应用类型,则默认调用 isAnyWebApplication 方法返回条件匹配结果。

3.1 isServletWebApplication 方法

我们直接翻看 isServletWebApplication 方法的源码,如下:

private ConditionOutcome isServletWebApplication(ConditionContext context) {
	ConditionMessage.Builder message = ConditionMessage.forCondition("");
	if (!ClassNameFilter.isPresent(SERVLET_WEB_APPLICATION_CLASS, context.getClassLoader())) {
		return ConditionOutcome.noMatch(message.didNotFind("servlet web application classes").atAll());
	}
	if (context.getBeanFactory() != null) {
		String[] scopes = context.getBeanFactory().getRegisteredScopeNames();
		if (ObjectUtils.containsElement(scopes, "session")) {
			return ConditionOutcome.match(message.foundExactly("'session' scope"));
		}
	}
	if (context.getEnvironment() instanceof ConfigurableWebEnvironment) {
		return ConditionOutcome.match(message.foundExactly("ConfigurableWebEnvironment"));
	}
	if (context.getResourceLoader() instanceof WebApplicationContext) {
		return ConditionOutcome.match(message.foundExactly("WebApplicationContext"));
	}
	return ConditionOutcome.noMatch(message.because("not a servlet web application"));
}

我们来详细分析一下:

  • 首先,检查类加载器中是否存在 org.springframework.web.context.support.GenericWebApplicationContext
    • 如果没有,那么将返回不匹配的结果,并附带消息 "did not find servlet web application classes"
  • 如果条件上下文 contextBeanFactory 不为空,则获取所有注册的 scope 名称,并检查其中是否包含 "session"。如果包含,则返回匹配的结果,并附带消息 "found session scope"
  • 如果条件上下文 contextEnvironmentConfigurableWebEnvironment 的实例,则将返回匹配的结果,并附带消息 "found ConfigurableWebEnvironment"
  • 如果条件上下文 contextResourceLoaderWebApplicationContext 的实例,那么将返回匹配的结果,并附带消息 "found WebApplicationContext"
  • 如果上述的条件都不满足,则最后将返回不匹配的结果,并附带消息 "not a servlet web application"

3.2 isReactiveWebApplication 方法

同样,我们也先来查看下 isReactiveWebApplication 方法的源码,如下:

private ConditionOutcome isReactiveWebApplication(ConditionContext context) {
	ConditionMessage.Builder message = ConditionMessage.forCondition("");
	if (!ClassNameFilter.isPresent(REACTIVE_WEB_APPLICATION_CLASS, context.getClassLoader())) {
		return ConditionOutcome.noMatch(message.didNotFind("reactive web application classes").atAll());
	}
	if (context.getEnvironment() instanceof ConfigurableReactiveWebEnvironment) {
		return ConditionOutcome.match(message.foundExactly("ConfigurableReactiveWebEnvironment"));
	}
	if (context.getResourceLoader() instanceof ReactiveWebApplicationContext) {
		return ConditionOutcome.match(message.foundExactly("ReactiveWebApplicationContext"));
	}
	return ConditionOutcome.noMatch(message.because("not a reactive web application"));
}

通过上述 isServletWebApplication 方法中的分析,我们可以很快总结下:

  • 首先,检查类加载器中是否存在 org.springframework.web.reactive.HandlerResult
    • 如果没有,那么将返回不匹配的结果,并附带消息 "did not find reactive web application classes"
  • 如果条件上下文 contextEnvironmentConfigurableReactiveWebEnvironment 的实例,则将返回匹配的结果,并附带消息 "found ConfigurableReactiveWebEnvironment"
  • 如果条件上下文 contextResourceLoaderReactiveWebApplicationContext 的实例,那么将返回匹配的结果,并附带消息 "found ReactiveWebApplicationContext"
  • 如果上述的条件都不满足,则最后将返回不匹配的结果,并附带消息 "not a reactive web application"

3.3 isAnyWebApplication 方法

还是一样,我们先来看看 isAnyWebApplication 方法的源码,如下:

private ConditionOutcome isAnyWebApplication(ConditionContext context, boolean required) {
	ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnWebApplication.class,
			required ? "(required)" : "");
	ConditionOutcome servletOutcome = isServletWebApplication(context);
	if (servletOutcome.isMatch() && required) {
		return new ConditionOutcome(servletOutcome.isMatch(), message.because(servletOutcome.getMessage()));
	}
	ConditionOutcome reactiveOutcome = isReactiveWebApplication(context);
	if (reactiveOutcome.isMatch() && required) {
		return new ConditionOutcome(reactiveOutcome.isMatch(), message.because(reactiveOutcome.getMessage()));
	}
	return new ConditionOutcome(servletOutcome.isMatch() || reactiveOutcome.isMatch(),
			message.because(servletOutcome.getMessage()).append("and").append(reactiveOutcome.getMessage()));
}

这里就更简单了,总结如下:

  • 首先,通过调用 isServletWebApplication 方法获取条件匹配结果;
    • 如果 Servlet Web 应用程序的条件结果匹配并且 requiredtrue,则返回一个包含匹配状态和相关消息的 ConditionOutcome 对象。
  • 接着,通过调用 isReactiveWebApplication 方法获取条件匹配结果;
    • 如果 Reactive Web 应用程序的条件结果匹配并且 requiredtrue,则同样返回一个包含匹配状态和相关消息的 ConditionOutcome 对象。
  • 最后,如果上述两种情况都不满足 或者 requiredfalse ,则返回一个新的 ConditionOutcome 对象,它包含 servletOutcome.isMatch() || reactiveOutcome.isMatch() 的匹配状态 和 servletOutcomereactiveOutcome 两者拼接的消息。

总结

本篇 Huazie 带大家从源码角度深入了解了自动配置过滤匹配子类 OnWebApplicationCondition ,至此 Spring Boot 中有关自动配置过滤匹配的三个实现已经介绍完毕,当然有关过滤匹配条件的内容还没结束,下一篇笔者将介绍 @Conditional 条件注解。


http://lihuaxi.xjx100.cn/news/1595749.html

相关文章

Vue Router的使用

使用 项目中注入路由器 在项目中 src 目录下新建 router 目录&#xff0c;其中包含 index.js 路由主文件。 // src/router/index.jsimport Vue from vue import Router from vue-router import { routes } from ./routes.jsVue.use(Router) const router new Router({route…

一座“城池”:泡泡玛特主题乐园背后,IP梦想照亮现实

“更适合中国宝宝体质”的主题乐园&#xff0c;被泡泡玛特造出来了。 9月26日&#xff0c;位于北京朝阳公园内的国内首个潮玩行业沉浸式 IP 主题乐园&#xff0c;也是泡泡玛特首个线下乐园——泡泡玛特城市乐园 POP LAND正式开园。 约4万平方米的空间中&#xff0c;泡泡玛特使…

python多线程与多进程

多线程与多进程 一, 什么是进程, 什么是线程? ​ 进程: 运行中的程序. 每次我们执行一个程序, 咱们的操作系统对自动的为这个程序准备一些必要的资源(例如, 分配内存, 创建一个能够执行的线程. ) ​ 线程: 程序内, 可以直接被CPU调度的执行过程. 是操作系统能够进行运算调度…

备忘录模式 行为型模式之八

1.定义 备忘录模式是一种行为型的软件设计模式&#xff0c;在不破坏封装的前提下&#xff0c;获取一个对象的内部状态&#xff0c;并在对象外保存该状态&#xff0c;当对象需要恢复到该状态时&#xff0c;对其进行恢复。 2.组成结构 原发器 &#xff08;Originator&#xff0…

SaaS 电商设计 (二) 全链路解决方案概述和核心业务流程梳理

一.业务目标&技术目标 业务目标:完成多业态,多渠道的数字化运营 自有业务: O2O,B2C,B2B2C,S2B2b 平台业务:POPB2c,POPB2b,POPS2B2b 1.1 自有业务 O2O:全称Online to Offline.泛指的线上线下的业务融合.这种的情况分为两种情况,第一种通过线上的数字化运营引导线上用户线下…

【版本控制工具一】Git 安装注册及使用

文章目录 一、Git 、Github、Gitee1.1 概述1.2 码云 相对于 github 的优势 二、Github 或 Gitee注册2.1 注册2.2 创建仓库 三、Git下载与安装四、创建本地仓库 一、Git 、Github、Gitee 1.1 概述 Git 是一个开源的分布式版本控制系统&#xff0c;用于敏捷高效地处理任何或小或…

【LeetCode高频SQL50题-基础版】打卡第2天:第11-15题

文章目录 【LeetCode高频SQL50题-基础版】打卡第2天&#xff1a;第11-15题⛅前言 员工奖金&#x1f512;题目&#x1f511;题解 学生们参加各科测试的次数&#x1f512;题目&#x1f511;题解 至少有5名直接下属的经理&#x1f512;题目&#x1f511;题解 确认率&#x1f512;题…

学习记忆——数学篇——案例——算术——记忆100内质数

文章目录 质数表歌诀记忆法100以内的质数歌谣质数口决一百以内质数口诀100以内素数歌 规律记忆法100以内6的倍数前、后位置上的两个数&#xff0c;只要不是5或7的倍数&#xff0c;就一定是质数个数没有用该数除以包括7在内的质数 分类记忆法数字编码法谐音记忆法 100以内的质数…