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 {

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

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Gerber文件使用详解

目录 概述 一、Gerber 格式 二、接线图示例 三、顶层丝印 四、顶级阻焊层 五、顶部助焊层 六、顶部&#xff08;或顶部铜&#xff09; 七、钻头 八、电路板概要 九、使用文本和字体进行 Gerber 导出 十、总结 概述 Gerber文件:它们是什么? PCB制造商如何使用它们? …

C# 编程新手必看,一站式学习网站,让你轻松掌握 C# 技能!

介绍&#xff1a;实际上&#xff0c;您可能弄错了&#xff0c;C#并不是一种独立的编程语言&#xff0c;而是一种由微软公司开发的面向对象的、运行于.NET Framework之上的高级程序设计语言。C#看起来与Java十分相似&#xff0c;但两者并不兼容。 C#的设计目标是简单、强大、类型…

智能优化算法应用:基于战争策略算法无线传感器网络(WSN)覆盖优化 - 附代码

智能优化算法应用&#xff1a;基于战争策略算法无线传感器网络(WSN)覆盖优化 - 附代码 文章目录 智能优化算法应用&#xff1a;基于战争策略算法无线传感器网络(WSN)覆盖优化 - 附代码1.无线传感网络节点模型2.覆盖数学模型及分析3.战争策略算法4.实验参数设定5.算法结果6.参考…

轻松操纵SQL:Druid解析器实践

一、背景 在BI&#xff08;Business Intelligence&#xff09;场景中&#xff0c;用户会频繁使用SQL查询语句&#xff0c;但在平台运作过程中&#xff0c;面临着权限管理、多数据源处理和表校验等多种挑战。 例如&#xff0c;用户可能不清楚自身是否具备对特定表&#xff08;…

极简模式,助力宏观数据监控

随着UWA GOT Online采样的参数越来越多样化&#xff0c;为了提升开发者的使用体验&#xff0c;我们最新推出了三种预设数据采集方案&#xff1a;极简模式、CPU模式、内存模式。该更新旨在降低多数据采集对数据准确性的干扰&#xff0c;同时也为大家提供更精准且有针对性的数据指…

15.Eclipse常用基本配置设置

在使用Eclipse进行Java开发之前&#xff0c;经常需要进行一些配置&#xff0c;其中有些配置甚至是必须的&#xff0c;即使开始不编辑之后开发过程中也会出一些因配置导致的小问题。本文梳理了一下Eclipse使用中常用的配置 1 编码配置 1.1 设置工作空间编码格式 打开Eclipse&…

甘草书店:#10 2023年11月24日 星期五 「麦田创业分享2—世界奇奇怪怪,请保持可可爱爱」

今日继续分享麦田创业经验。 如果你问我&#xff0c;创业过程中是否想过放弃。那么答案是&#xff0c;有那么一次。 那时想要放弃的原因并不是辛苦没有回报&#xff0c;或是资金短缺&#xff0c;而是没能理解“异见者”。 其实事情非常简单&#xff0c;现在反观那时的自己&a…

在360极速模式下解决使用sortable拖拽元素会启用360文字拖拽功能问题

拖拽元素禁止时&#xff0c;加提示语句 会弹出搜索页签, 因为360自带选中文字&#xff0c;启用搜索引擎的功能,如图所示 苦恼了两天 问了大佬&#xff0c;实际是使用了自带还原生的H5拖拽功能&#xff0c;而sortable.js组件有一个属性forceFallback , 将该属性设置为true 就…

pwn入门:基本栈溢出之ret2libc详解(以32位+64位程序为例)

目录 写在开头 题目简介 解题思路 前置知识&#xff08;简要了解&#xff09; plt表和got表 延迟绑定 例题详解 32位 64位 总结与思考 写在开头 这篇博客早就想写了&#xff0c;但由于近期事情较多&#xff0c;一直懒得动笔。近期被领导派去临时给合作单位当讲师&a…

Private Set Intersection from Pseudorandom CorrelationGenerators 最快PSI!导览解读

目录 一、概述 二、相关介绍 三、性能对比 四、技术细节 1.KKRT 2.Pseudorandom Correlation Generators 3.A New sVOLE-Based BaRK-OPRF 4.BaRK-OPRF 五、总结 参考文献 一、概述 这篇文章的主要脉络和核心思想是探讨如何利用伪随机相关生成器&#xff08;PCG&#…

在Asp.Net Core中启用Http响应压缩

无论是开发网站&#xff0c;还是开发Api。很多时候为了节约网络流量我们需要对请求金星压缩处理以减少消息传递过程中的资源消耗&#xff0c;并且多数情况有利于应用发挥更好的性能&#xff08;响应压缩在服务端处理&#xff0c;使用服务器资源&#xff09;。 在Asp.Net Core中…

EasyExcel-最简单的读写excel工具类

前言&#xff1a; easyExcel 的官网文档给的示例非常全&#xff0c;可以参考https://easyexcel.opensource.alibaba.com/docs/current/quickstart/read 在此我贴出自己的工具类&#xff0c;可以直接用 导包 <dependency><groupId>com.alibaba</groupId><…

问题:batchnormal训练单个batch_size就会报错吗

Batch Normalization&#xff08;批标准化&#xff09;是一种深度学习中的正则化技巧&#xff0c;它可以改进网络的训练过程。在训练神经网络时&#xff0c;Batch Normalization可以帮助解决内部协变量偏移&#xff08;Internal Covariate Shift&#xff09;的问题。 在标准的…

PyTorch2.0环境搭建

一、安装python并配置环境变量 1、打开python官网&#xff0c;下载并安装 Welcome to Python.org 下载 寻找版本&#xff1a;推荐使用3.9版本&#xff0c;或其他表中显示为安全&#xff08;security&#xff09;的版本 安装&#xff1a;&#xff08;略&#xff09; 2、配置环…

apisix下自定义 Nginx 配置

apisix下自定义 Nginx 配置 在apisix配置文件/conf/config.yaml中添加nginx配置。生成的nginx.conf配置文件如下&#xff1a;说明&#xff1a; APISIX 会通过 apisix/cli/ngx_tpl.lua 这个模板和 conf/config-default.yaml 加 conf/config.yaml 的配置生成 Nginx 配置文件。 在…

爱智EdgerOS之深入解析如何在EdgerOS中使用SQLite3数据库引擎

一、SQLite 简介 数据管理是应用开发者最常遇到的挑战之一&#xff0c;无论是支付宝的余额&#xff0c;或是京东购物车里的商品&#xff0c;都需要存储在对应服务后端的数据库中&#xff0c;以满足用户查询、转账、购买等各种各样的使用场景。EdgerOS 智能边缘计算操作系统内置…

【模型量化】神经网络量化基础及代码学习总结

1 量化的介绍 量化是减少神经网络计算时间和能耗的最有效的方法之一。在神经网络量化中&#xff0c;权重和激活张量存储在比训练时通常使用的16-bit或32-bit更低的比特精度。当从32-bit降低到8-bit&#xff0c;存储张量的内存开销减少了4倍&#xff0c;矩阵乘法的计算成本则二…

【展望2024】,从软件测试用例开始学习起

1. 测试用例的概念 测试用例就是测试人员向被测试系统发起的一组集合&#xff0c;该集合包括测试环境&#xff0c;测试数据&#xff0c;测试步骤&#xff0c;预期结果 2. 设计测试用例的好处 在测试前都要先设计测试用例&#xff0c;设计测试用例有如下好处&#xff1a; 测…

从 0 到 100TB,MatrixOne 助您轻松应对

作者&#xff1a;邓楠MO产品总监 导读 随着传感器和网络技术的大规模应用&#xff0c;海量 IoT 设备产生了巨量数据&#xff0c;传统数据库方案难以满足这些数据的存储和处理需求。MatrixOne 是一款强大的云原生超融合数据库&#xff0c;具备优秀的流式数据写入和加工能力&am…