首页天道酬勤transactional注解生效范围,一个阶段的结束意味着

transactional注解生效范围,一个阶段的结束意味着

张世龙 05-12 08:15 80次浏览

1、SpringApplication正常终止springboot2.0springapplication正常终止SpringApplicationRunListener的生命周期,即running (此方法用于spring APP包EventPublishingRunListener是spring应用程序runner的唯一内置实现,这种方法只方便地广播应用程序readyevent事件。

@ overridepublicvoidrunning (configurableapplicationcontextcontext ) context.publish event (newapplicationreadyevent ) aple }触发}SpringApplicationreadyevent事件后,spring应用程序的生命周期,除非springapplicationrunlisteners # running方法执行异常

publicconfigurableapplicationcontextrun (字符串…args )…try (监听器. running ) context ); } catch (可移植ex ) handlerunfailure )上下文,ex,exceptionReporters,null ); thrownewillegalstateexception (ex; }返回上下文; 换言之,开发者通过两种技术手段实现完成阶段的拦截。 一个是为了实现springapplicationrunlisteners # running方法,另一个是为了实现ApplicationReadyEvent事件的SpringApplicationListener。

2、SpringApplication异常终止SpringApplication异常终止宣告spring boot APP应用程序执行失败。 与常规流程一样,异常流程也是SpringApplication生命周期的一部分,配置可配置应用程序上下文(springapplicationrunlistener # failed )

2.1、Spring Boot异常处理privatevoidhandlerunfailure (可配置应用程序上下文上下文,可配置执行, collectionspringbootexceptionreporterexceptionreporters,springapplicationrunlistenerslisteners ) { try { handleeexitcoder }=null (listeners.failed (上下文,exception ) ); } finally { report failure (exception reporters,exception ); if (上下文!=null(context.close ); }}catch(exceptionex ) logger.warn (' unabletocloseapplicationcontext ',ex ); } reflection utils.rethrowruntimeexception (exception ); } Spring Boot异常处理主要由两部分组成。 一个是结束代码处理,另一个是异常报告。 结束代码处理在《Spring Boot应用退出》中说明。 这里分析异常报告。

Spring Boot2.0中添加了SpringBootExceptionReporter接口。 这是一个回调接口,支持定制报告SpringApplication启动错误。

publicinterfacespringbootexceptionreporter { booleanreportexception (可移动故障); SpringBootExceptionReporter集合在初始化过程中包含getspringfactoriesinstances (springbootexceptionreporter.class, newclass[]{cclass}因此,如果要自定义SpringBootExceptionReporter,请使用ConfigurableApplicationContext参数在Spring Boot2.x中

final class FailureAnalyzers impl

ements 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)方法调用执行:

@Overridepublic 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);@Overridepublic 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 analyzersorg.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中经常出现。

什么是红线,idea红色波浪线是什么警告