SpringBoot自动配置源码解析+自定义Spring Boot Starter

news2024/10/5 10:31:28

@SpringBootApplication

        Spring Boot应用标注 @SpringBootApplication 注解的类说明该类是Spring Boot 的主配置类,需要运行该类的main方法进行启动 Spring Boot 应用

@SpringBootConfiguration

       该注解标注表示标注的类是个配置类

@EnableAutoConfiguration

        直译:开启自动配置

@AutoConfigurationPackage

        将当前配置类所在的包保存在 basePackages 的Bean 中,提供给Spring 使用

@Import(AutoConfigurationPackages.Registrar.class)

      注册一个保存当前配置类所在包的Bean

@Import(AutoConfigurationImportSelector.class)

        使用@Import注解完成导入AutoConfigurationImportSelector类 的功能。AutoConfigurationImportSelector 实现了DeferredImportSelector类

注:在解析ImportSelector时,所导入的配置类会被直接解析,而DeferredImportSelector导入的配置类会延迟进行解析(延迟在其他配置类都解析完之后)

        Spring容器在解析@Import时会去执行DeferredImportSelector 的 selectImports方法:

/**
	 * Return the {@link AutoConfigurationEntry} based on the {@link AnnotationMetadata}
	 * of the importing {@link Configuration @Configuration} class.
	 * @param annotationMetadata the annotation metadata of the configuration class
	 * @return the auto-configurations that should be imported
	 */
	protected AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
		if (!isEnabled(annotationMetadata)) {
			return EMPTY_ENTRY;
		}
		AnnotationAttributes attributes = getAttributes(annotationMetadata);
        // 从META-INF/spring.factories中获得候选的自动配置类
		List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
        //去重
		configurations = removeDuplicates(configurations);
        //根据EnableAutoConfiguration注解中exclude、excludeName属性、
        //spring.autoconfigure.exclude 配置的排除项
		Set<String> exclusions = getExclusions(annotationMetadata, attributes);
		checkExcludedClasses(configurations, exclusions);
		configurations.removeAll(exclusions);
        // 通过读取spring.factories 中        
        // OnBeanCondition\OnClassCondition\OnWebApplicationCondition进行过滤
		configurations = getConfigurationClassFilter().filter(configurations);
		fireAutoConfigurationImportEvents(configurations, exclusions);
		return new AutoConfigurationEntry(configurations, exclusions);
	}

        springboot应用中都会引入spring-boot-autoconfigure依赖,spring.factories文件就在该包的META-INF下面。spring.factories文件是Key=Value形式,多个Value时使用“,”逗号进行分割,该文件中定义了关于初始化、监听器、过滤器等信息,而真正使自动配置生效的key是org.springframework.boot.autoconfigure.EnableAutoConfiguration,如下所示:

Spring Boot 提供的自动配置类

   https://docs.spring.io/spring-boot/docs/current/reference/html/auto-configuration-classes.html#appendix.auto-configuration-classes

Spring Boot 常用条件注解

        ConditionalOnBean:是否存在某个某类或某个名字的Bean
        ConditionalOnMissingBean:是否缺失某个某类或某个名字的Bean
        ConditionalOnSingleCandidate:是否符合指定类型的Bean只有一个
        ConditionalOnClass:是否存在某个类
        ConditionalOnMissingClass:是否缺失某个类
        ConditionalOnExpression:指定的表达式返回的是true还是false
        ConditionalOnJava:判断Java版本
        ConditionalOnWebApplication:当前应用是不是一个Web应用
        ConditionalOnNotWebApplication:当前应用不是一个Web应用
        ConditionalOnProperty:Environment中是否存在某个属性

        我们也可以使用@Conditional注解进行自定义条件注解

        条件注解可以写在类和方法上,如果某个@xxxCondition条件注解写在自动配置类上,那该自动配置类会不会生效就要看当前条件是否符合条件,或者条件注解写在某个@Bean修饰的方法上,那么Bean生不生效也要看当前的条件是否符条件。

        Spring容器在解析某个自动配置类时,会先判断该自动配置类上是否有条件注解,如果有,则进一步判断条件注解所指定的条件当前情况是否满足,如果满足,则继续解析该配置类,如果不满足则不进行解析该配置类,于是配置类所定义的Bean也都得不到解析,那么在Spring容器中就不会存在该Bean。
        同理,Spring在解析某个@Bean的方法时,也会先判断方法上是否有条件注解,然后进行解析,如果不满足条件,则该Bean也不会生效。

        Spring Boot提供的自动配置,实际上就是Spring Boot源码中预先写好准备了一些常用的配置类,预先定义好了一些Bean,在用Spring Boot时,这些配置类就已经在我们项目的依赖中了,而这些自动配置类或自动配置Bean是否生效,就需要看具体指定的条件是否满足。

        下面代码就是根据 @Conditional 确定是否应跳过忽略

/**
	 * Determine if an item should be skipped based on {@code @Conditional} annotations.
	 * @param metadata the meta data
	 * @param phase the phase of the call
	 * @return if the item should be skipped
	 */
	public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata, @Nullable ConfigurationPhase phase) {
		if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) {
			return false;
		}

		if (phase == null) {
			if (metadata instanceof AnnotationMetadata &&
					ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata) metadata)) {
				return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION);
			}
			return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
		}

		List<Condition> conditions = new ArrayList<>();
		for (String[] conditionClasses : getConditionClasses(metadata)) {
			for (String conditionClass : conditionClasses) {
				Condition condition = getCondition(conditionClass, this.context.getClassLoader());
				conditions.add(condition);
			}
		}

		AnnotationAwareOrderComparator.sort(conditions);

		for (Condition condition : conditions) {
			ConfigurationPhase requiredPhase = null;
			if (condition instanceof ConfigurationCondition) {
				requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
			}
			if ((requiredPhase == null || requiredPhase == phase) && 
// 重点判断
!condition.matches(this.context, metadata)) {
				return true;
			}
		}

		return false;
	}

以@ConditionalOnBean底层工作原理为示例

        OnBeanCondition类继承了FilteringSpringBootCondition,FilteringSpringBootCondition类又继承SpringBootCondition,而SpringBootCondition实现了Condition接口,matches()方法也是在
SpringBootCondition这个类中实现的:

public abstract class SpringBootCondition implements Condition {

	private final Log logger = LogFactory.getLog(getClass());

	@Override
	public final boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// 获取当前解析的类名或方法名
		String classOrMethodName = getClassOrMethodName(metadata);
		try {
// 进行具体的条件匹配,ConditionOutcome表示匹配结果
			ConditionOutcome outcome = getMatchOutcome(context, metadata);
//日志记录匹配结果
			logOutcome(classOrMethodName, outcome);
			recordEvaluation(context, classOrMethodName, outcome);
// 返回匹配结果 true/false
			return outcome.isMatch();
		}
		catch (NoClassDefFoundError ex) {
			throw new IllegalStateException("Could not evaluate condition on " + classOrMethodName + " due to "
					+ ex.getMessage() + " not found. Make sure your own configuration does not rely on "
					+ "that class. This can also happen if you are "
					+ "@ComponentScanning a springframework package (e.g. if you "
					+ "put a @ComponentScan in the default package by mistake)", ex);
		}
		catch (RuntimeException ex) {
			throw new IllegalStateException("Error processing condition on " + getName(metadata), ex);
		}
	}
//....
	public abstract ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata);

}

        具体的条件匹配逻辑在getMatchOutcome方法中实现的,而SpringBootCondition类中的
getMatchOutcome方法是一个抽象方法,具体的实现逻辑就在子类OnBeanCondition:

@Override
	public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
		ConditionMessage matchMessage = ConditionMessage.empty();
		MergedAnnotations annotations = metadata.getAnnotations();
        // 如果存在ConditionalOnBean注解
		if (annotations.isPresent(ConditionalOnBean.class)) {
			Spec<ConditionalOnBean> spec = new Spec<>(context, metadata, annotations, ConditionalOnBean.class);
			MatchResult matchResult = getMatchingBeans(context, spec);
            // 如果某个Bean不存在
			if (!matchResult.isAllMatched()) {
				String reason = createOnBeanNoMatchReason(matchResult);
				return ConditionOutcome.noMatch(spec.message().because(reason));
			}
            // 所有Bean都存在
			matchMessage = spec.message(matchMessage)
				.found("bean", "beans")
				.items(Style.QUOTE, matchResult.getNamesOfAllMatches());
		}
    // 如果存在ConditionalOnSingleCandidate注解
		if (metadata.isAnnotated(ConditionalOnSingleCandidate.class.getName())) {
			Spec<ConditionalOnSingleCandidate> spec = new SingleCandidateSpec(context, metadata, annotations);
			MatchResult matchResult = getMatchingBeans(context, spec);
			if (!matchResult.isAllMatched()) {
				return ConditionOutcome.noMatch(spec.message().didNotFind("any beans").atAll());
			}
			Set<String> allBeans = matchResult.getNamesOfAllMatches();
			if (allBeans.size() == 1) {
				matchMessage = spec.message(matchMessage).found("a single bean").items(Style.QUOTE, allBeans);
			}
			else {
				List<String> primaryBeans = getPrimaryBeans(context.getBeanFactory(), allBeans,
						spec.getStrategy() == SearchStrategy.ALL);
				if (primaryBeans.isEmpty()) {
					return ConditionOutcome
						.noMatch(spec.message().didNotFind("a primary bean from beans").items(Style.QUOTE, allBeans));
				}
				if (primaryBeans.size() > 1) {
					return ConditionOutcome
						.noMatch(spec.message().found("multiple primary beans").items(Style.QUOTE, primaryBeans));
				}
				matchMessage = spec.message(matchMessage)
					.found("a single primary bean '" + primaryBeans.get(0) + "' from beans")
					.items(Style.QUOTE, allBeans);
			}
		}
        // 存在ConditionalOnMissingBean注解
		if (metadata.isAnnotated(ConditionalOnMissingBean.class.getName())) {
			Spec<ConditionalOnMissingBean> spec = new Spec<>(context, metadata, annotations,
					ConditionalOnMissingBean.class);
			MatchResult matchResult = getMatchingBeans(context, spec);
			if (matchResult.isAnyMatched()) {
				String reason = createOnMissingBeanNoMatchReason(matchResult);
				return ConditionOutcome.noMatch(spec.message().because(reason));
			}
			matchMessage = spec.message(matchMessage).didNotFind("any beans").atAll();
		}
		return ConditionOutcome.match(matchMessage);
	}


protected final MatchResult getMatchingBeans(ConditionContext context, Spec<?> spec) {
		ClassLoader classLoader = context.getClassLoader();
		ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
		boolean considerHierarchy = spec.getStrategy() != SearchStrategy.CURRENT;
		Set<Class<?>> parameterizedContainers = spec.getParameterizedContainers();
		if (spec.getStrategy() == SearchStrategy.ANCESTORS) {
			BeanFactory parent = beanFactory.getParentBeanFactory();
			Assert.isInstanceOf(ConfigurableListableBeanFactory.class, parent,
					"Unable to use SearchStrategy.ANCESTORS");
			beanFactory = (ConfigurableListableBeanFactory) parent;
		}
		MatchResult result = new MatchResult();
		Set<String> beansIgnoredByType = getNamesOfBeansIgnoredByType(classLoader, beanFactory, considerHierarchy,
				spec.getIgnoredTypes(), parameterizedContainers);
		for (String type : spec.getTypes()) {
			Collection<String> typeMatches = getBeanNamesForType(classLoader, considerHierarchy, beanFactory, type,
					parameterizedContainers);
			typeMatches
				.removeIf((match) -> beansIgnoredByType.contains(match) || ScopedProxyUtils.isScopedTarget(match));
			if (typeMatches.isEmpty()) {
				result.recordUnmatchedType(type);
			}
			else {
				result.recordMatchedType(type, typeMatches);
			}
		}
		for (String annotation : spec.getAnnotations()) {
			Set<String> annotationMatches = getBeanNamesForAnnotation(classLoader, beanFactory, annotation,
					considerHierarchy);
			annotationMatches.removeAll(beansIgnoredByType);
			if (annotationMatches.isEmpty()) {
				result.recordUnmatchedAnnotation(annotation);
			}
			else {
				result.recordMatchedAnnotation(annotation, annotationMatches);
			}
		}
		for (String beanName : spec.getNames()) {
			if (!beansIgnoredByType.contains(beanName) && containsBean(beanFactory, beanName, considerHierarchy)) {
				result.recordMatchedName(beanName);
			}
			else {
				result.recordUnmatchedName(beanName);
			}
		}
		return result;
	}

        getMatchingBeans方法中会利用BeanFactory去获取指定类型的Bean,如果没有指定类型的Bean,则会将该类型记录在MatchResult对象的unmatchedTypes集合中,如果有该类型的Bean,则会把该Bean的beanName记录在MatchResult对象的matchedNames集合中,所以MatchResult对象中记录了哪些类没有对应的Bean,哪些类有对应的Bean。

        大概流程如下:

        Spring在解析某个配置类,或某个Bean定义时如果发现它们上面用到了条件注解,就会取出所有的条件注解,并生成对应的条件对象,比如OnBeanCondition对象;
        依次调用条件对象的matches方法,进行条件匹配,看是否符合条件
        条件匹配逻辑中,会拿到@ConditionalOnBean等条件注解的信息,判断哪些Bean存在
        然后利用BeanFactory来进行判断
        最后只有所有条件注解的条件都匹配,那么当前Bean定义才算符合条件生效

自定义Spring Boot Starter

        SpringBoot 最强大的功能就是把我们常用的业务场景抽取成了一个个starter(场景启动器),我们通过引入SpringBoot 提供的这些场景启动器,再进行少量的配置就能使用相应的功能。但是,SpringBoot 不能囊括我们所有的业务使用场景,往往我们需要自定义starter,来简化我们对springboot的使用。

        下面是自定义starter的示例代码地址:

lp-springboot-start: 自定义Spring Boot Start

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1669557.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

日本率先研发成功6G设备,刺痛了谁?为何日本能率先突破?

日本率先研发成功6G设备&#xff0c;无线数据速率是5G的百倍&#xff0c;这让日本方面兴奋莫名&#xff0c;毕竟日本在科技方面从1990年代以来太缺少突破的创新了&#xff0c;那么日本为何如今在6G技术上能率先突破呢&#xff1f; 日本在1980年代末期达到顶峰&#xff0c;它的科…

华为OD机试 - 求幸存数之和(Java 2024 C卷 100分)

华为OD机试 2024C卷题库疯狂收录中&#xff0c;刷题点这里 专栏导读 本专栏收录于《华为OD机试&#xff08;JAVA&#xff09;真题&#xff08;A卷B卷C卷&#xff09;》。 刷的越多&#xff0c;抽中的概率越大&#xff0c;每一题都有详细的答题思路、详细的代码注释、样例测试…

python将图片以及标注信息按类别分开

目录 需求&#xff1a; 思路&#xff1a; 原数据集结构&#xff1a; 代码1&#xff08;效率低&#xff0c;但不用提前知道需要分多少个类别&#xff09;&#xff1a; 代码2&#xff08;效率相对高点&#xff0c;但类别数量如果超过设定的11个&#xff0c;则需要改下代码&a…

MySQL·索引

目录 索引的意义 索引的理解 为何IO交互要是 Page 理解Page 其他数据结构为何不行&#xff1f; 聚簇索引 VS 非聚簇索引 索引操作 主键索引操作 唯一键索引操作 普通索引的创建 总结 全文索引 索引的意义 索引&#xff1a;提高数据库的性能&#xff0c;索引是物美…

[AIGC] 压缩列表了解吗?快速列表 quicklist 了解吗?

文章目录 压缩列表了解吗&#xff1f;快速列表 quicklist 了解吗&#xff1f; 压缩列表了解吗&#xff1f; 压缩列表是 Redis 为了节约内存 而使用的一种数据结构&#xff0c;是由一系列特殊编码的连续内存快组成的顺序型数据结构。 一个压缩列表可以包含任意多个节点&#xf…

ae如何导出mp4格式?图文教程,手把手教您搞定

在创作精彩的视频内容后&#xff0c;将其成功导出为通用的MP4格式是确保作品在不同平台上流畅播放的重要一环。Adobe After Effects作为一款专业的视频后期制作工具&#xff0c;提供了丰富的功能来实现这一目标。在本文中&#xff0c;我们将通过图文教程&#xff0c;手把手地向…

人生是旷野,不是轨道

最近看到一句话&#xff0c;很喜欢&#xff0c;分享一下。"人生是旷野&#xff0c;不是轨道"。人生不是固定的方程式&#xff0c;也没有唯一答案&#xff0c;没有谁生来就应该是什么样。别太被太多世俗观念束缚住手脚&#xff0c;每个人都有权利自由生长&#xff0c;…

【Ubuntu】apt命令安装最新版本Nginx

目录 环境前言添加Nginx仓库步骤1、仓库公钥2、文本公钥转二进制GPG公钥&#xff08;可选&#xff09;3、添加apt软件源4、安装新版Nginx 参阅 环境 Ubuntu 22.04 前言 ubuntu官方apt软件仓库&#xff08;或者叫软件源&#xff09;的软件版本可能会比较旧&#xff0c;导致无…

Unity 性能优化之GPU Instancing(五)

提示&#xff1a;仅供参考&#xff0c;有误之处&#xff0c;麻烦大佬指出&#xff0c;不胜感激&#xff01; 文章目录 前言一、GPU Instancing使用方法二、使用GPU Instancing的条件三、GPU Instancing弊端四、注意五、检查是否成功总结 前言 GPU Instancing也是一种Draw call…

xCode升级后: Library ‘iconv2.4.0’ not found

报错信息&#xff1a; targets 选中 xxxNotification: Build Phases ——> Link Binary With Libraries 中&#xff0c;移除 libiconv.2.4.0.tbd libiconv.2.4.0.dylib 这两个库&#xff08;只有一个的移除一个就好&#xff09;。 然后重新添加 libiconv.tbd 修改完…

如何将Git仓库中的文件打包成zip文件?

要将Git仓库中的文件打包成zip文件&#xff0c;您可以使用git archive命令。这个命令允许您将任何git可访问的树或提交导出成一个归档文件。以下是一些基本的步骤&#xff1a; 打开命令行或终端。切换到您的Git仓库的目录。执行git archive命令。 git archive --formatzip --o…

【ARMv8/v9 系统寄存器 5 -- CPU ID 判断寄存器 MPIDR_EL1 使用详细介绍】

文章目录 寄存器名称: MPIDR_EL1寄存器结构:主要功能和用途亲和级别&#xff08;Affinity Levels&#xff09;简介CORE ID 获取函数 在ARMv8-A架构中&#xff0c; MPIDR_EL1寄存器是一个非常重要的系统寄存器&#xff0c;它提供了关于处理器在其物理和逻辑配置中的位置的信息。…

力扣:48. 旋转图像(Java)

目录 题目描述&#xff1a;输入&#xff1a;输出&#xff1a;代码实现&#xff1a; 题目描述&#xff1a; 给定一个 n n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。 你必须在 原地 旋转图像&#xff0c;这意味着你需要直接修改输入的二维矩阵。请不要 使…

STM32快速入门(定时器之输出PWM波形)

STM32快速入门&#xff08;定时器之输出PWM波形&#xff09; 前言 本节主要讲解STM32利用通用定时器&#xff0c;利用CCR和CNT寄存器&#xff0c;输出指定占空比和频率的PWM波形。其功能的应用有&#xff1a;实现LED呼吸灯的效果、控制步进电机、控制直流电机转速等。 导航 …

GUI Pro - Survival Clean

通过开发生存游戏的经验,我们制作了一个带有科幻概念的GUI包。我们希望这个包对你的项目有所帮助。 主要特征 - 2560x1440分辨率图形 - GUI皮肤,包含布局演示场景和预制件 - 提供各种象形图标和项目图标 - 切片元素和白色元素,可定制尺寸和颜色 - 不包括编码和动画 资产 - 1…

栈和队列OJ练习题及解答

前言 上一篇博客已经讲到了栈和队列的数据结构&#xff0c;概括一下&#xff1a;栈后进先出&#xff08;Last In First Out&#xff09;、队列先进先出&#xff08;First In First Out&#xff09;。那么&#xff0c;接下来就来讲讲&#xff0c;关于栈和队列的相关练习题&#…

蓝桥杯-线性动态规划问题背包问题进阶策略详解-

题目&#xff1a;蓝桥云课-青蛙吃虫 解题代码&#xff1a; #include <iostream> #include<cstring> #include<algorithm> using namespace std;const int N106;int f[N][N]; int a[N]; int t,l,r,k,n;int main() {cin>>t;while(t--){scanf("%d%…

FANUC机器人初始化系统的基本方法和步骤

FANUC机器人初始化系统的基本方法和步骤 首先,在做系统初始化之前,必须做好系统的备份,这里做个镜像备份,更详细的镜像备份步骤可参考以下链接中的内容: FANUC机器人进行全部备份和镜像备份以及加载备份文件的具体操作(图文) 如下图所示,在示教器右边的USB接口上插个…

Android finishInputEvent 流程分析

InputDispatcher将事件分发给应用程序后&#xff0c;将该event放入connection的wq队列中&#xff0c;APP处理完之后&#xff0c;需要发送一个完成的信号给InputDispatcher&#xff0c;以供InputDispatcher来将该event从wq队列中移除。我们来分析这个过程。 我们知道&#xff0…

图文详解:synchronized关键字 及其底层原理

目录 一.线程安全问题 二.synchronized关键字 ▐ synchronized图解 ▐ 可重入锁及图解 ▐ synchronized用于方法上 三.Java标准库中synchronized的使用 四.synchronized的底层实现原理 一.线程安全问题 线程安全是指在多线程环境下&#xff0c;对共享资源的访问不会导致…