SpringApplication_一个阶段结束

SpringApplication_一个阶段结束1、SpringApplication正常结束SpringBoot2.0为SpringApplication正常结束新引入了SpringApplicationRunListener的生命周期,即running(ConfigurableApplicationContext),该方法在Spring应用上下文中已准备,并且CommandLineRunner和ApplicationRunnerBean均已执行完毕。EventPublishingRunListener作为SpringApplicationRu

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

1、SpringApplication正常结束

Spring Boot2.0为SpringApplication正常结束新引入了SpringApplicationRunListener的生命周期,即running(ConfigurableApplicationContext),该方法在Spring应用上下文中已准备,并且CommandLineRunner和ApplicationRunner Bean均已执行完毕。EventPublishingRunListener作为Spring ApplicationRunner 唯一内建实现,本方法中仅简单地广播ApplicationReadyEvent事件:

	@Override
	public void running(ConfigurableApplicationContext context) { 
   
		context.publishEvent(new ApplicationReadyEvent(this.application, this.args, context));
	}

不难看出当ApplicationReadyEvent事件触发后,SpringApplication的生命周期进入尾声,除非SpringApplicationRunListeners#running方法执行异常:

	public ConfigurableApplicationContext run(String... args) { 
   
		...
		try { 
   
			listeners.running(context);
		}
		catch (Throwable ex) { 
   
			handleRunFailure(context, ex, exceptionReporters, null);
			throw new IllegalStateException(ex);
		}
		return context;
	}

换言之,开发人员有两种技术手段实现完成阶段的监听,一种为实现SpringApplicationRunListeners#running方法,另一种为实现ApplicationReadyEvent事件的SpringApplicationListener。

2、SpringApplication异常结束

SpringApplication异常结束就宣告Spring Boot应用运行失败。与正常流程类似,异常流程同样作为SpringApplication生命周期的一个环节,将在SpringApplicationRunListener#failed(ConfigurableApplicationContext, Throwable)方法。

2.1、Spring Boot异常处理

	private void handleRunFailure(ConfigurableApplicationContext context, Throwable exception,
			Collection<SpringBootExceptionReporter> exceptionReporters, SpringApplicationRunListeners listeners) { 
   
		try { 
   
			try { 
   
				handleExitCode(context, exception);
				if (listeners != null) { 
   
					listeners.failed(context, exception);
				}
			}
			finally { 
   
				reportFailure(exceptionReporters, exception);
				if (context != null) { 
   
					context.close();
				}
			}
		}
		catch (Exception ex) { 
   
			logger.warn("Unable to close ApplicationContext", ex);
		}
		ReflectionUtils.rethrowRuntimeException(exception);
	}

Spring Boot异常处理主要包含两部分:一是退出码处理,二是异常报告。退出码处理放在《Spring Boot应用退出》中讲解,这里这要分析异常报告。
在Spring Boot2.0中新增了一个SpringBootExceptionReporter接口,用于支持SpringApplication启动错误的自定义报告的回调接口。

public interface SpringBootExceptionReporter { 
   

	boolean reportException(Throwable failure);

}

由于SpringBootExceptionReporter 集合在初始化过程中,明确地执行了getSpringFactoriesInstances(SpringBootExceptionReporter.class,new Class[] { ConfigurableApplicationContext.class }, context);语句,所以当自定义SpringBootExceptionReporter 时,必须用一个ConfigurableApplicationContext参数声明一个公共构造函数,比如Spring Boot2.x内建唯一实现FailureAnalyzers:

final class FailureAnalyzers implements SpringBootExceptionReporter { 
   

	private static final Log logger = LogFactory.getLog(FailureAnalyzers.class);

	private final ClassLoader classLoader;

	private final List<FailureAnalyzer> analyzers;

	FailureAnalyzers(ConfigurableApplicationContext context) { 
   
		this(context, null);
	}

	FailureAnalyzers(ConfigurableApplicationContext context, ClassLoader classLoader) { 
   
		Assert.notNull(context, "Context must not be null");
		this.classLoader = (classLoader != null) ? classLoader : context.getClassLoader();
		this.analyzers = loadFailureAnalyzers(this.classLoader);
		prepareFailureAnalyzers(this.analyzers, context);
	}
	...
}

可简单地认为FailureAnalyzers 是FailureAnalyzer的组合类,在其构造阶段通过Spring工厂加载机制初始化并排序FailureAnalyzer列表:

	private List<FailureAnalyzer> loadFailureAnalyzers(ClassLoader classLoader) { 
   
		List<String> analyzerNames = SpringFactoriesLoader.loadFactoryNames(FailureAnalyzer.class, classLoader);
		List<FailureAnalyzer> analyzers = new ArrayList<>();
		for (String analyzerName : analyzerNames) { 
   
			try { 
   
				Constructor<?> constructor = ClassUtils.forName(analyzerName, classLoader).getDeclaredConstructor();
				ReflectionUtils.makeAccessible(constructor);
				analyzers.add((FailureAnalyzer) constructor.newInstance());
			}
			catch (Throwable ex) { 
   
				logger.trace(LogMessage.format("Failed to load %s", analyzerName), ex);
			}
		}
		AnnotationAwareOrderComparator.sort(analyzers);
		return analyzers;
	}
	
	private void prepareFailureAnalyzers(List<FailureAnalyzer> analyzers, ConfigurableApplicationContext context) { 
   
		for (FailureAnalyzer analyzer : analyzers) { 
   
			prepareAnalyzer(context, analyzer);
		}
	}

	private void prepareAnalyzer(ConfigurableApplicationContext context, FailureAnalyzer analyzer) { 
   
		if (analyzer instanceof BeanFactoryAware) { 
   
			((BeanFactoryAware) analyzer).setBeanFactory(context.getBeanFactory());
		}
		if (analyzer instanceof EnvironmentAware) { 
   
			((EnvironmentAware) analyzer).setEnvironment(context.getEnvironment());
		}
	}

加载后的FailureAnalyzer列表作为FailureAnalyzers#(Throwable, List<FailureAnalyzer>)方法的参数,随着SpringApplication#(Collection<SpringBootExceptionReporter>, Throwable)方法调用执行:

	@Override
	public boolean reportException(Throwable failure) { 
   
		FailureAnalysis analysis = analyze(failure, this.analyzers);
		return report(analysis, this.classLoader);
	}

	private FailureAnalysis analyze(Throwable failure, List<FailureAnalyzer> analyzers) { 
   
		for (FailureAnalyzer analyzer : analyzers) { 
   
			try { 
   
				FailureAnalysis analysis = analyzer.analyze(failure);
				if (analysis != null) { 
   
					return analysis;
				}
			}
			catch (Throwable ex) { 
   
				logger.debug(LogMessage.format("FailureAnalyzer %s failed", analyzer), ex);
			}
		}
		return null;
	}
	
	private boolean report(FailureAnalysis analysis, ClassLoader classLoader) { 
   
		List<FailureAnalysisReporter> reporters = SpringFactoriesLoader.loadFactories(FailureAnalysisReporter.class,
				classLoader);
		if (analysis == null || reporters.isEmpty()) { 
   
			return false;
		}
		for (FailureAnalysisReporter reporter : reporters) { 
   
			reporter.report(analysis);
		}
		return true;
	}

不难看出FailureAnalyzer仅分析故障,而故障报告则由FailureAnalysisReporter 对象负责。

2.2、错误分析报告器——FailureAnalysisReporter

同样地FailureAnalysisReporter也由Spring工厂加载机制初始化并排序。在Spring Boot框架中仅存在一个内建FailureAnalysisReporter的实现LoggingFailureAnalysisReporter。

public final class LoggingFailureAnalysisReporter implements FailureAnalysisReporter { 
   

	private static final Log logger = LogFactory.getLog(LoggingFailureAnalysisReporter.class);

	@Override
	public void report(FailureAnalysis failureAnalysis) { 
   
		if (logger.isDebugEnabled()) { 
   
			logger.debug("Application failed to start due to an exception", failureAnalysis.getCause());
		}
		if (logger.isErrorEnabled()) { 
   
			logger.error(buildMessage(failureAnalysis));
		}
	}

	private String buildMessage(FailureAnalysis failureAnalysis) { 
   
		StringBuilder builder = new StringBuilder();
		builder.append(String.format("%n%n"));
		builder.append(String.format("***************************%n"));
		builder.append(String.format("APPLICATION FAILED TO START%n"));
		builder.append(String.format("***************************%n%n"));
		builder.append(String.format("Description:%n%n"));
		builder.append(String.format("%s%n", failureAnalysis.getDescription()));
		if (StringUtils.hasText(failureAnalysis.getAction())) { 
   
			builder.append(String.format("%nAction:%n%n"));
			builder.append(String.format("%s%n", failureAnalysis.getAction()));
		}
		return builder.toString();
	}

}

与FailureAnalysisReporter不同的是,FailureAnalyzer的内建实现相当丰富,下面是org.springframework.boot:spring-boot-autoconfigure:2.3.0中的META-INF/spring.factories:

# Failure analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.boot.autoconfigure.diagnostics.analyzer.NoSuchBeanDefinitionFailureAnalyzer,\
org.springframework.boot.autoconfigure.flyway.FlywayMigrationScriptMissingFailureAnalyzer,\
org.springframework.boot.autoconfigure.jdbc.DataSourceBeanCreationFailureAnalyzer,\
org.springframework.boot.autoconfigure.jdbc.HikariDriverConfigurationFailureAnalyzer,\
org.springframework.boot.autoconfigure.session.NonUniqueSessionRepositoryFailureAnalyzer

其中NoSuchBeanDefinitionFailureAnalyzer和DataSourceBeanCreationFailureAnalyzer在Spring Boot中经常出现。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/195760.html原文链接:https://javaforall.net

(0)
上一篇 2025年10月10日 下午10:43
下一篇 2025年10月10日 下午11:22


相关推荐

  • OpenClaw自定义模型Windows安装教程

    OpenClaw自定义模型Windows安装教程

    2026年3月14日
    1
  • slf4j与log4j、log4j2

    slf4j与log4j、log4j2nbsp nbsp 最近公司项目系统需要将日志从 log4j slf4j 升级为 log4j2 然后彻彻底底的把它们研究了一遍 在网上查找相关资源 发现并没有一篇文章能够很完整的把它们之间的关联和区别写出来 所以我在这里做一个总结 log4j nbsp nbsp 如果在我们系统中单独使用 log4j 的话 我们只需要引入 log4j 的核心包就可以了 我这里用的是 log4j 1 2 17 jar 然后在系统中使用如下代码输出日志 pu

    2026年3月19日
    3
  • KOBAS 3.0学习

    KOBAS 3.0学习在线通路注释 一般使用 DAVID KASS KOBAS 等工具 Kobas KOBAS 基于 KEGGOrtholog 是用于基因 蛋白质功能注释 注释模块 和功能集富集 Enrichmentmo 的 Web 服务器 给定一组基因或蛋白质 它可以确定通路 疾病和基因本体论 GO 术语是否显示统计学显着性 KOBAS3 0 由两个功能

    2026年3月19日
    2
  • python解释器在语法上不支持_语法测试

    python解释器在语法上不支持_语法测试1.安装Flake8必须在console中进行安装,示:pipinstallflake82.配置PycharmProgram:$PyInterpreterDirectory$/pythonarguments:-mflake8–max-line-length=130–excludevenv,migrations$ProjectFileDir$wor…

    2025年11月9日
    6
  • 常见NoSQL数据库概述

    常见NoSQL数据库概述我们再日常的运维中 应用及接触最多无疑是关系型数据库了 尤其以开源的为主 Mysql MariaDB Postgrelsql 等 然后随着业务的复杂 数据量及类型的快速转变 我们不得不考虑更多数据库满足我们的业务需要 必须时序性的 全文检索的 k v 的 即时查询的 图形的 音视频的等等 作为运维 我们也不得不了解并掌握其中最常用的典型代表

    2026年3月17日
    1
  • 微信养号防封攻略_防封群微信怎么卖「建议收藏」

    微信养号防封攻略_防封群微信怎么卖「建议收藏」任何企业或者个人做营销或者推广等等一切都离不开微信,有很多企业和个人的生存渠道就是微信,如果把微信号封了,几乎是断了他们生存的机会,在这样的大环境下,把自己企业和个人的微信号养好,就成了非常重要的一个环节。微信能安全使用,是所有一切的基础。但是很多人现在还不懂的去操作养号,这几天我个人也陆续有号被封,所以我就整理了一下微信养号的操作方法。自己可以使用,也顺便分享给更多的人,这个操作方法涵盖了微信每天养号需要必须要操作的动作,这些动作是每天必须要操作的。先说一下微信权重的影响因素微信养号一、微信权重

    2022年5月15日
    97

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号