当前位置: 首页 > news >正文

SpringBoot事件机制

SpringBoot事件机制

启动入口

SpringApplication.run(H2Application.class, args);方法

public ConfigurableApplicationContext run(String... args) {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		DefaultBootstrapContext bootstrapContext = createBootstrapContext();
		ConfigurableApplicationContext context = null;
		configureHeadlessProperty();
		SpringApplicationRunListeners listeners = getRunListeners(args);
    	//1.发送ApplicationStartingEvent事件,回调starting
		listeners.starting(bootstrapContext, this.mainApplicationClass);
		try {
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            //2.发送ApplicationEnvironmentPreparedEvent事件,回调environmentPrepared,
            //listeners.environmentPrepared(bootstrapContext, environment);
			ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
			configureIgnoreBeanInfo(environment);
			Banner printedBanner = printBanner(environment);
			context = createApplicationContext();
			context.setApplicationStartup(this.applicationStartup);
            //3.listeners.contextPrepared(context);
            //4.listeners.contextLoaded(context);
			prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
			refreshContext(context);
			afterRefresh(context, applicationArguments);
			stopWatch.stop();
			if (this.logStartupInfo) {
				new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
			}
            //5.ApplicationStartedEvent事件 listeners.started(context);
			listeners.started(context);
			callRunners(context, applicationArguments);
		}
		catch (Throwable ex) {
            //ApplicationFailedEvent
			handleRunFailure(context, ex, listeners);
			throw new IllegalStateException(ex);
		}

		try {
            //6.ApplicationReadyEvent事件 listeners.running(context);
			listeners.running(context);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, null);
			throw new IllegalStateException(ex);
		}
		return context;
	}

事件整理

事件含义:

事件名称回调方法含义主要动作
ApplicationStartingEventstartingSpirng应用开始了
ApplicationEnvironmentPreparedEventenvironmentPrepared应用环境变量配置完成
ApplicationContextInitializedEventcontextPrepared准备ApplicationContext
ApplicationPreparedEventcontextLoaded完成ApplicationContext
ApplicationStartedEventstartedSpring应用启动结束;执行ApplicationRunner和CommandLineRunner
ApplicationReadyEventrunningSpring应用正式启动完成
ApplicationFailedEventfailedSpring应用启动失败

自定义事件

复用SpringBoot内置事件机制,自定义,参考:context.publishEvent(new ExitCodeEvent(context, exitCode));

定阅事件

@Component
public class UserRegisterSendSMSListener implements ApplicationListener<UserRegisterEvent> {
 
    private static final Logger LOGGER = LoggerFactory.getLogger(UserRegisterSendSMSListener.class);
 
    @Override
    public void onApplicationEvent(UserRegisterEvent userRegisterEvent) {
        // 发送短信
        LOGGER.info("新注册用户 {} 短信发送成功", userRegisterEvent.getUser().getUserName());
    }
}

发布事件

@RestController
@RequestMapping("user")
public class UserController {
 
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
 
    @PostMapping
    public String register(@RequestBody UserModel model) {
        // 验证
        // 注册
        // 事件
        UserRegisterEvent userRegisterEvent = new UserRegisterEvent(this, model);
        applicationEventPublisher.publishEvent(userRegisterEvent);
        return Boolean.TRUE.toString();
    }
}

自定义监听

package com.dxz.controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

public class SampleSpringApplicationRunListener implements SpringApplicationRunListener {
    private final SpringApplication application;
    private final String[] args;
	
    //任何一个SpringApplicationRunListener实现类的构造方法都需要有两个构造参数,一个参数的类型就是我们的org.springframework.boot.SpringApplication,另外一个参数就是args参数列表的String[]
    public SampleSpringApplicationRunListener(SpringApplication sa, String[] args) {
        this.application = sa;
        this.args = args;
    }

    @Override
    public void starting() {
        System.out.println("自定义starting");
    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
        System.out.println("自定义environmentPrepared");
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        System.out.println("自定义contextPrepared");
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        System.out.println("自定义contextLoaded");
    }

    @Override
    public void finished(ConfigurableApplicationContext context, Throwable exception) {
        System.out.println("自定义finished");
    }
}
org.springframework.boot.SpringApplicationRunListener=\
    com.dxz.SampleSpringApplicationRunListener

相关文章:

  • IDEA配置tomcat以及创建项目
  • Node.js | 使用内置模块 event 实现发布订阅模式
  • 七千字详解javaString类
  • 希尔排序算法
  • synchronized同步以及双重检索
  • Codeforce8.29-9.4做题笔记
  • springboot+宴会预定平台 毕业设计-附源码231718
  • python super()详解,一篇文章告诉你python的super是什么,如何使用
  • Redis 的持久化
  • 2022年中国证券行业智能投顾专题分析
  • MYSQL高可用架构之MHA实战(真实可用)
  • 【Reinforcement Learning】蒙特卡洛算法
  • SAP ABAP ADT安装说明 as 20220901
  • 计算机组成原理知识总结(八)输入/输出系统
  • springboot基于java的康泰小区物业管理系统的设计与实现毕业设计源码101926
  • 【笔记】你不知道的JS读书笔记——Promise
  • AzureCon上微软宣布了哪些容器相关的重磅消息
  • CentOS6 编译安装 redis-3.2.3
  • Docker容器管理
  • gulp 教程
  • Laravel 实践之路: 数据库迁移与数据填充
  • oschina
  • SpiderData 2019年2月23日 DApp数据排行榜
  • 从0到1:PostCSS 插件开发最佳实践
  • 警报:线上事故之CountDownLatch的威力
  • 老板让我十分钟上手nx-admin
  • 配置 PM2 实现代码自动发布
  • 前端之React实战:创建跨平台的项目架构
  • 设计模式 开闭原则
  • 深入浅出Node.js
  • 算法-图和图算法
  • 微服务框架lagom
  • 小而合理的前端理论:rscss和rsjs
  • 异常机制详解
  • 用 Swift 编写面向协议的视图
  • [Shell 脚本] 备份网站文件至OSS服务(纯shell脚本无sdk) ...
  • 7行Python代码的人脸识别
  • mysql 慢查询分析工具:pt-query-digest 在mac 上的安装使用 ...
  • ​Linux Ubuntu环境下使用docker构建spark运行环境(超级详细)
  • ​ssh-keyscan命令--Linux命令应用大词典729个命令解读
  • (17)Hive ——MR任务的map与reduce个数由什么决定?
  • (6)【Python/机器学习/深度学习】Machine-Learning模型与算法应用—使用Adaboost建模及工作环境下的数据分析整理
  • (JS基础)String 类型
  • (附源码)springboot 校园学生兼职系统 毕业设计 742122
  • (七)Knockout 创建自定义绑定
  • (三) diretfbrc详解
  • (十) 初识 Docker file
  • (一)ClickHouse 中的 `MaterializedMySQL` 数据库引擎的使用方法、设置、特性和限制。
  • (原創) 如何動態建立二維陣列(多維陣列)? (.NET) (C#)
  • ./include/caffe/util/cudnn.hpp: In function ‘const char* cudnnGetErrorString(cudnnStatus_t)’: ./incl
  • .NET Remoting学习笔记(三)信道
  • .NET 发展历程
  • .netcore 获取appsettings
  • .net利用SQLBulkCopy进行数据库之间的大批量数据传递
  • .net连接oracle数据库