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

news2024/10/7 16:19:31

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 {

    @Override
    public 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 {


    @Override
    public 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> {

    @Override
    public 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;
    }


    @Override
    public void starting() {
        log.info("starting...");
    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
        log.info("environmentPrepared...");

    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        log.info("contextPrepared...");
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        log.info("contextLoaded...");
    }

    @Override
    public void started(ConfigurableApplicationContext context) {
        log.info("started...");
    }

    @SneakyThrows
    @Override
    public 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);
    }

    @Override
    public 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 start
            listeners.started(context);
            // 调用所有的Runner
            this.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.coloradmin.cn/o/1296834.html

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

相关文章

机器学习之无监督学习:九大聚类算法

今天&#xff0c;和大家分享一下机器学习之无监督学习中的常见的聚类方法。 今天&#xff0c;和大家分享一下机器学习之无监督学习中的常见的聚类方法。 在无监督学习中&#xff0c;我们的数据并不带有任何标签&#xff0c;因此在无监督学习中要做的就是将这一系列无标签的数…

idea使用maven的package打包时提示“找不到符号”或“找不到包”

介绍&#xff1a;由于我们的项目是多模块开发项目&#xff0c;在打包时有些模块内容更新导致其他模块在引用该模块时不能正确引入。 情况一&#xff1a;找不到符号 情况一&#xff1a;找不到包 错误代码部分展示&#xff1a; Failure to find com.xxx.xxxx:xxx:pom:0.5 in …

NLP项目实战01之电影评论分类

介绍&#xff1a; 欢迎来到本篇文章&#xff01;在这里&#xff0c;我们将探讨一个常见而重要的自然语言处理任务——文本分类。具体而言&#xff0c;我们将关注情感分析任务&#xff0c;即通过分析电影评论的情感来判断评论是正面的、负面的。 展示&#xff1a; 训练展示如下…

ABAP - Function ALV 01 Function ALV的三大基石

森莫是Function ALV&#xff1f; 业务顾问和用户方面的名词定义为报表&#xff0c;在开发顾问方面定义的名词为ALV 通过调用Function方式展示的ALV叫做FunctionALV.Function的解释:封装好的函数 Function ALV的三大基石 Fieldcat :Function ALV字段级别的处理 Layout …

CentOS服务自启权威指南:手动启动变为开机自启动(以Jenkins服务为例)

前言 CentOS系统提供了多种配置服务开机自启动的方式。本文将介绍其中两种常见的方式&#xff0c; 一种是使用Systemd服务管理器配置&#xff0c;不过&#xff0c;在实际中&#xff0c;如果你已经通过包管理工具安装的&#xff0c;那么服务通常已经被配置为Systemd服务&#…

利用法线贴图渲染逼真的3D老虎模型

在线工具推荐&#xff1a; 3D数字孪生场景编辑器 - GLTF/GLB材质纹理编辑器 - 3D模型在线转换 - Three.js AI自动纹理开发包 - YOLO 虚幻合成数据生成器 - 三维模型预览图生成器 - 3D模型语义搜索引擎 当谈到游戏角色的3D模型风格时&#xff0c;有几种不同的风格&#xf…

让聪明的车连接智慧的路,C-V2X开启智慧出行生活

“聪明的车 智慧的路”形容的便是车路协同的智慧交通系统&#xff0c;从具备无钥匙启动&#xff0c;智能辅助驾驶和丰富娱乐影音功能的智能网联汽车&#xff0c;到园区的无人快递配送车&#xff0c;和开放的城市道路上自动驾驶的公交车、出租车&#xff0c;越来越多的车联网应用…

ELK(四)—els基本操作

目录 elasticsearch基本概念RESTful API创建非结构化索引&#xff08;增&#xff09;创建空索引&#xff08;删&#xff09;删除索引&#xff08;改&#xff09;插入数据&#xff08;改&#xff09;数据更新&#xff08;查&#xff09;搜索数据&#xff08;id&#xff09;&…

【Copilot】Edge浏览器的copilot消失了怎么办

这种原因&#xff0c;可能是因为你的ip地址的不在这个服务的允许范围内。你需要重新使用之前出现copilot的ip地址&#xff0c;然后退出edge的账号&#xff0c;重新登录一遍&#xff0c;最后重启edge&#xff0c;就能够使得copilot侧边栏重新出现了。

mac苹果电脑清除数据软件CleanMyMac X4.16

在数字时代&#xff0c;保护个人隐私变得越来越重要。当我们出售个人使用的电脑&#xff0c;亦或者离职后需要上交电脑&#xff0c;都需要对存留在电脑的个人信息做彻底的清除。随着越来越多的人选择使用苹果电脑&#xff0c;很多人想要了解苹果电脑清除数据要怎样做才是最彻底…

Endnote在word中加入参考文献及自定义参考文献格式方式

第一部分&#xff1a;在word中增加引用步骤 1、先下载对应文献的endnote引用格式&#xff0c;如在谷歌学术中的下载格式如下&#xff1a; 2、在endnote中打开存储env的格式库&#xff0c;导入对应下载的文件格式&#xff1a;file>import>file>choose,import对应文件&a…

套接字应用程序

这章节是关于实现 lib_chan 库的 。 lib_chan 的代码在 TCP/IP 之上实现了一个完整的网络层&#xff0c;能够提供认证和Erlang 数据流功能。一旦理解了 lib_chan 的原理&#xff0c;就能量身定制我们自己的通信基础结构&#xff0c;并把它叠加在TCP/IP 之上了。 就lib_chan 本身…

PSP - 计算蛋白质复合物链间接触的残基与面积

欢迎关注我的CSDN&#xff1a;https://spike.blog.csdn.net/ 本文地址&#xff1a;https://spike.blog.csdn.net/article/details/134884889 在蛋白质复合物中&#xff0c;通过链间距离&#xff0c;可以计算出在接触面的残基与接触面的面积&#xff0c;使用 BioPython 库 与 SA…

在Pytorch中使用Tensorboard可视化训练过程

这篇是我对哔哩哔哩up主 霹雳吧啦Wz 的视频的文字版学习笔记 感谢他对知识的分享 本节课我们来讲一下如何在pytouch当中去使用我们的tensorboard 对我们的训练过程进行一个可视化 左边有一个visualizing models data and training with tensorboard 主要是这么一个教程 那么这里…

28BYJ-48步进电机的驱动

ULN2003的工作原理 28BYJ48可以用ULN2003来驱动&#xff0c;STM32使用开漏模式外接5V上拉电阻也可以产生5V电压&#xff0c;为什么不直接使用单片机的 GPIO来驱动的原因是虽然电压符合电机的驱动要求&#xff0c;但单片机引脚产生的驱动电流太小&#xff0c;因此驱动步进电机要…

IBM Qiskit量子机器学习速成(四)

量子核机器学习 一般步骤 量子核机器学习的一般步骤如下 定义量子核 我们使用FidelityQuantumKernel类创建量子核&#xff0c;该类需要传入两个参数&#xff1a;特征映射和忠诚度(fidelity)。如果我们不传入忠诚度&#xff0c;该类会自动创建一个忠诚度。 注意各个类所属的…

leaflet:经纬度坐标转为地址,点击鼠标显示地址信息(137)

第137个 点击查看专栏目录 本示例的目的是介绍演示如何在vue+leaflet中将经纬度坐标转化为地址,点击鼠标显示某地的地址信息 。主要利用mapbox的api将坐标转化为地址,然后在固定的位置显示出来。 直接复制下面的 vue+leaflet源代码,操作2分钟即可运行实现效果 文章目录 示…

UniDBGrid序号列添加标题

有人想要在UniDBGrid的序号列加上标题&#xff0c;就是这里 可以使用如下代码 UniSession.AddJS(MainForm.UniDBGrid1.columnManager.columns[0].setText("序号"));

VMware安装Ubuntu20.04并使用Xshell连接虚拟机

文章目录 虚拟机环境准备重置虚拟网络适配器属性&#xff08;可选&#xff09;配置NAT模式的静态IP创建虚拟机虚拟机安装配置 Xshell连接虚拟机 虚拟机环境准备 VMware WorkStation Pro 17.5&#xff1a;https://customerconnect.vmware.com/cn/downloads/details?downloadGr…

样本数量对问卷信度效度分析的影响及应对策略

问卷调研是一种常见的数据收集方法。明确问卷的真实性和效率是保证其靠谱性和有效性的重要一步。但问卷的真实性和品质会受到样本数量的影响吗&#xff1f; 一、问卷信度的认识 1、信度的概念和重要性:在问卷实验中&#xff0c;信度是指问卷测量值的稳定性和一致性。高信度代…