前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot系列之启动成功后执行业务的方法归纳

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

作者头像
SmileNicky
发布2023-12-09 10:37:32
2830
发布2023-12-09 10:37:32
举报
文章被收录于专栏:Nicky's blogNicky's blog

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容器扫描到

代码语言:javascript
复制
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接口

代码语言:javascript
复制
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启动成功后做一些业务操作

代码语言:javascript
复制
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,可以在对应方法进行拓展即可

代码语言:javascript
复制
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配置文件配置:

代码语言:javascript
复制
org.springframework.boot.SpringApplicationRunListener=\
  com.example.jedis.listener.TestSpringApplicationRunListener
在这里插入图片描述
在这里插入图片描述

源码分析

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

代码语言:javascript
复制
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);
        }
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023-12-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 实验环境
  • 动手实践
  • 源码分析
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档