SpringBoot系列之启动成功后执行业务的方法归纳

SpringBoot系列之启动成功后执行业务逻辑。在Springboot项目中经常会遇到需要在项目启动成功后,加一些业务逻辑的,比如缓存的预处理,配置参数的加载等等场景,下面给出一些常有的方法

实验环境

  • JDK 1.8
  • SpringBoot 2.2.1
  • Maven 3.2+
  • Mysql 8.0.26
  • 开发工具
    • IntelliJ IDEA

    • smartGit

动手实践

  • ApplicationRunner和CommandLineRunner

比较常有的使用Springboot框架提供的ApplicationRunnerCommandLineRunner,这两种Runner可以实现在Springboot项目启动后,执行我们自定义的业务逻辑,然后执行的顺序可以通过@Order进行排序,参数值越小,越早执行

写个测试类实现ApplicationRunner接口,注意加上@Component才能被Spring容器扫描到

package com.example.jedis.runner;import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;@Order(1)
@Component
@Slf4j
public class TestApplicationRunner implements ApplicationRunner {@Overridepublic void run(ApplicationArguments args) throws Exception {log.info("TestApplicationRunner");}
}

在这里插入图片描述

实现CommandLineRunner接口

package com.example.jedis.runner;import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;@Order(2)
@Component
@Slf4j
public class TestCommandLineRunner implements CommandLineRunner {@Overridepublic void run(String... args) throws Exception {log.info("TestCommandLineRunner");}
}

在这里插入图片描述

  • ApplicationListener加ApplicationStartedEvent

SpringBoot基于Spring框架的事件监听机制,提供ApplicationStartedEvent可以对SpringBoot启动成功后的监听,基于事件监听机制,我们可以在SpringBoot启动成功后做一些业务操作

package com.example.jedis.listener;import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;@Component
@Slf4j
public class TestApplicationListener implements ApplicationListener<ApplicationStartedEvent> {@Overridepublic void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {log.info("onApplicationEvent");}
}

在这里插入图片描述

  • SpringApplicationRunListener

如果要在启动的其它阶段做业务操作,可以实现SpringApplicationRunListener接口,例如要实现打印swagger的api接口文档url,可以在对应方法进行拓展即可

package com.example.jedis.listener;import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;import java.net.InetAddress;@Slf4j
public class TestSpringApplicationRunListener implements SpringApplicationRunListener {private final SpringApplication application;private final String[] args;public TestSpringApplicationRunListener(SpringApplication application, String[] args) {this.application = application;this.args = args;}@Overridepublic void starting() {log.info("starting...");}@Overridepublic void environmentPrepared(ConfigurableEnvironment environment) {log.info("environmentPrepared...");}@Overridepublic void contextPrepared(ConfigurableApplicationContext context) {log.info("contextPrepared...");}@Overridepublic void contextLoaded(ConfigurableApplicationContext context) {log.info("contextLoaded...");}@Overridepublic void started(ConfigurableApplicationContext context) {log.info("started...");}@SneakyThrows@Overridepublic void running(ConfigurableApplicationContext context) {log.info("running...");ConfigurableEnvironment environment = context.getEnvironment();String port = environment.getProperty("server.port");String contextPath = environment.getProperty("server.servlet.context-path");String docPath = port + "" + contextPath + "/doc.html";String externalAPI = InetAddress.getLocalHost().getHostAddress();log.info("\n Swagger API: "+ "Local-API: \t\thttp://127.0.0.1:{}\n\t"+ "External-API: \thttp://{}:{}\n\t",docPath, externalAPI, docPath);}@Overridepublic void failed(ConfigurableApplicationContext context, Throwable exception) {log.info("failed...");}
}

在/META-INF/spring.factories配置文件配置:

org.springframework.boot.SpringApplicationRunListener=\com.example.jedis.listener.TestSpringApplicationRunListener

在这里插入图片描述

源码分析

在Springboot的run方法里找到如下的源码,大概看一下就可以知道里面是封装了对RunnerSpringApplicationRunListener的调用

public ConfigurableApplicationContext run(String... args) {StopWatch stopWatch = new StopWatch();stopWatch.start();ConfigurableApplicationContext context = null;Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();this.configureHeadlessProperty();SpringApplicationRunListeners listeners = this.getRunListeners(args);// SpringApplicationRunListener调用listeners.starting();Collection exceptionReporters;try {ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);this.configureIgnoreBeanInfo(environment);Banner printedBanner = this.printBanner(environment);context = this.createApplicationContext();exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);this.refreshContext(context);this.afterRefresh(context, applicationArguments);stopWatch.stop();if (this.logStartupInfo) {(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);}// SpringApplicationRunListener startlisteners.started(context);// 调用所有的Runnerthis.callRunners(context, applicationArguments);} catch (Throwable var10) {this.handleRunFailure(context, var10, exceptionReporters, listeners);throw new IllegalStateException(var10);}try {// SpringApplicationRunListener running执行listeners.running(context);return context;} catch (Throwable var9) {this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);throw new IllegalStateException(var9);}}

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于ssm家庭理财系统源码和论文

基于ssm家庭理财系统源码和论文743 idea 数据库mysql5.7 数据库链接工具&#xff1a;navcat,小海豚等 环境&#xff1a; jdk8 tomcat8.5 开发技术 ssm 摘要 随着Internet的发展&#xff0c;人们的日常生活已经离不开网络。未来人们的生活与工作将变得越来越数字化&#xff…

英文论文查重复率网址

大家好&#xff0c;今天来聊聊英文论文查重复率网址&#xff0c;希望能给大家提供一点参考。 以下是针对论文重复率高的情况&#xff0c;提供一些修改建议和技巧&#xff1a; 英文论文查重复率网址 在撰写英文论文时&#xff0c;查重是确保论文原创性和质量的重要环节快码论文…

解决:During handling of the above exception, another exception occurred

解决&#xff1a;During handling of the above exception, another exception occurred 文章目录 解决&#xff1a;During handling of the above exception, another exception occurred背景报错问题报错翻译报错位置代码报错原因解决方法参考内容&#xff1a;今天的分享就到…

【页面】表格展示

展示 Dom <template><div class"srch-result-container"><!--左侧--><div class"left"><div v-for"(item,index) in muneList" :key"index" :class"(muneIndexitem.mm)?active:"click"pa…

车载测试:如何用CANape进行ADAS实车功能测试?

前言 CANape是一款用于ECU测量、标定、诊断以及ADAS传感器数据采集的工具型软件。 测量——通过CANape不仅能采集记录ECU内部信号&#xff0c;还支持与车辆上的各种传感器的总线进行通信。与ECU不同&#xff0c;ADAS传感器不提供车辆实际运行信号&#xff0c;而是提供车辆运行…

数据结构与算法(六)分支限界法(Java)

目录 一、简介1.1 定义1.2 知识回顾1.3 两种解空间树1.4 三种分支限界法1.5 回溯法与分支线定法对比1.6 使用步骤 二、经典示例&#xff1a;0-1背包问题2.1 题目2.2 分析1&#xff09;暴力枚举2&#xff09;分支限界法 2.3 代码实现1&#xff09;实现广度优先策略遍历2&#xf…

Linux shell编程学习笔记34:eval 命令

0 前言 在JavaScript语言中&#xff0c;有一个很特别的函数eval&#xff0c;eval函数可以将字符串当做 JavaScript 代码执行&#xff0c;返回表达式或值。 在Linux Shell 中也提供了内建命令eval&#xff0c;它是否具有JavaScript语言中eval函数的功能呢&#xff1f; 1 eval命…

kubesphere安装后启用DevOps

官方文档&#xff1a;KubeSphere DevOps 系统 1、集群管理---定制资源定义 进入目录&#xff1a;集群管理---定制资源定义搜索&#xff1a;clusterconfiguration 点击 ks-installer 右侧的 &#xff0c;选择编辑 YAML 在该 YAML 文件中&#xff0c;搜索 devops&#xff0c;…

快速安装Axure RP Extension for Chrome插件

打开原型文件的html&#xff0c;会跳转到这个页面&#xff0c;怎么破&#xff1f; 我们点开产品设计的原型图如果没有下载Axure插件是打不开&#xff0c;而我们国内网通常又不能再google商店搜索对应插件&#xff0c;下面教大家如何快速安装 1、打开原型文件->resources-&g…

一文搞懂全连接算法和它的作用

如果你是搞AI算法的同学&#xff0c;相信你在很多地方都见过全连接层。 无论是处理图片的卷积神经网络&#xff08;CNN&#xff09;&#xff0c;还是处理文本的自然语言处理&#xff08;NLP&#xff09;网络&#xff0c;在网络的结尾做分类的时候&#xff0c;总是会出现一个全…

实现SQL server数据库完整性

1.创建一个数据库名为“erp” 主数据文件&#xff1a;初始容量为5MB&#xff0c;最大容量为50MB&#xff0c;递增量为1MB&#xff0c;其余参数自设。事务日志文件&#xff1a;初始容量为3MB&#xff0c;最大容量为20MB&#xff0c;递增量为10%&#xff0c;其余参数自设。 创建…

【从零认识ECS云服务器 | 快速上线个人网站】三、对外发布网站

3.1 配置域名 用户是如何访问网站的呢&#xff1f; 用户在浏览器(IE、Chrome、FireFox等)上输入域名&#xff0c;如&#xff1a;http://www.aliyun.com &#xff1b; 浏览器自动调用DNS&#xff08;域名服务&#xff09;将域名解析为IP地址&#xff0c;如&#xff1a;123.123…