SpringBoot3核心原理

news2024/9/23 23:27:39

SpringBoot3核心原理

事件和监听器

生命周期监听

场景:监听应用的生命周期

可以通过下面步骤自定义SpringApplicationRunListener来监听事件。
①、编写SpringApplicationRunListener实现类
②、在META-INF/spring.factories中配置org.springframework.boot.SpringApplicationRunListener=自己的Listener,还可以指定一个有参构造器,接收两个参数SpringApplication application, String[] args
③、springboot在spring-boot.jar中配置了默认的Listener,如下:
org.springframework.boot.SpringApplicationRunListener=
org.springframework.boot.context.event.EventPublishingRunListener
监听器.png

场景实现
创建监听器

MyApplicationListener

package com.louis.listener;

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

import java.time.Duration;

/**
 * springboot应用生命周期监听
 * @author XRY
 * @date 2023年07月14日14:51
 */
public class MyApplicationListener implements SpringApplicationRunListener {
    @Override
    public void starting(ConfigurableBootstrapContext bootstrapContext) {
        System.out.println("===========starting==========正在启动=======");
    }

    @Override
    public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
        System.out.println("===========environmentPrepared==========环境准备完成=======");
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        //相当与IOC容器
        System.out.println("===========contextPrepared==========ioc容器准备完成=======");
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        System.out.println("===========contextLoaded==========ioc容器加载完成=======");
    }

    @Override
    public void started(ConfigurableApplicationContext context, Duration timeTaken) {
        System.out.println("===========started==========启动完成=======");
    }

    @Override
    public void ready(ConfigurableApplicationContext context, Duration timeTaken) {
        System.out.println("===========ready==========准备就绪=======");
    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {
        System.out.println("===========failed==========应用启动失败=======");
    }
}

提示:

想要让配置的监听器生效,需要在根目录下创建一个META-INF文件夹并添加文件spring.factories(它是一个key,value写法:key为接口全类名, value为我们创建类的全类名)

org.springframework.boot.SpringApplicationRunListener=com.louis.listener.MyApplicationListener
springboot应用生命周期监听

Listener先要从BootStrapContext引导整个项目启动,主要分为下面的几个步骤:

  1. 引导:利用BootstrapContext引导整个项目启动

    starting:应用开始,调用SpringApplication的run方法,只要有了BootStrapContext就执行
    environmentPrepared:环境准备好(把启动参数等绑定到环境变量中),但是ioc容器还没有创建。(调一次)
    
  2. 启动:

    contextPrepared: ioc容器创建并准备好,但是sources(主配置类)没加载,并关闭上下文,组件还没有创建(调一次)
    contextLoaded: ioc容器加载。著配置类加载进去,但是ioc容器还没有刷新。(Bean都没创建)
    started: ioc容器刷新了(容器中加入了Bean),但是runner没调用。
    ready: ioc容器刷新了(容器中加入了Bean),所有runner调用完。

  3. 运行

    以前的步骤都正确执行,代表容器running
    生命周期全流程.png

事件触发时机

1、各种回调监听器介绍
监听器监听阶段作用使用场景
BootstrapRegistryInitializer感知特定阶段感知引导初始化META-INF/spring.factories
创建引导上下文bootstrapContext的时候触发可以在主程序调用:application.add.BootstrapRegistryInitializer()
进行密钥校对授权
ApplicationContextInitializer感知特定阶段感知ioc容器初始化META-INF/spring.factories
ApplicationListener感知全阶段基于事件机制,感知事件。@Bean或EventListener、SpringApplication.addListeners(…)或SpringApplicationBuilder.listeners(…)、META-INF/spring.factories
SpringApplicationRunListener感知全阶段生命周期+各种阶段自定义操作META-INF/spring.factories
ApplicationRunner感知特定阶段感知应用就绪Ready的@Bean
CommandLineRunner感知特定阶段感知应用就绪Ready的@Bean

总结:

如果项目启动前做事:BootstrapRegistryInitializer和ApplicationContextInitializer
如果想要在项目启动完成后做事:ApplicationRunner和CommandLineRunner
如果想要干涉生命周期:SpringApplicationRunListener
如果想要用事件机制:ApplicationListener

2、事件完整触发流程(9种事件)
  • ApplicationStartingEvent:应用启动但未做任何事情,
  • ApplicationEnvironmentPreparedEvent:Environment准备好,但context未创建
  • ApplicationContextInitializedEvent:ApplicationContext准备好,ApplicationContextInitializers调用,到那时任何bean未加载
  • ApplicationPreparedEvent:容器刷新之前,bean定义信息加载
  • ApplicationStartedEvent:容器刷新完成,runner未调用
  • AvailabilityChangeEvent:LivenessState.CORRECT应用存活,存活探针
  • ApplicationReadyEvent:任何runner被调用
  • AvailabilityChangeEvent:ReadinessState.ACCEPTING_TRAFFIC应用就绪,可以接收请求,就绪探针
  • ApplicationFailedEvent:启动出错

事件发送顺序

事件发送顺序.png
**两个探针的作用是感知应用是否存货和就绪。 **

3、SpringBoot事件驱动开发

应用启动过程生命周期事件感知(9大事件)、应用运行中事件感知(无数种)

  • 事件发布:ApplicationEventPublisherAware或注入:ApplicationEventMulticaser
  • 事件监听:组件 + @EventListener
示例

事件驱动开发.png

创建service

AccountService

@Service
public class AccountService {
    public void addAccountScore(String username){
        System.out.println(username + "加了1分");
    }
}

CouponService

@Service
public class CouponService {
    public void sendCoupon(String username){
        System.out.println(username + "随机得到了一张优惠券");
    }
}

SystemService

@Service
public class SystemService {
    public void recordLog(String username, String password){
        System.out.println(username + "  ,密码为" + password + "登录信息已被记录");
    }
}
不使用事件

LoginController

@RestController
public class LoginController {

    @Autowired
    AccountService accountService;
    @Autowired
    CouponService couponService;
    @Autowired
    SystemService systemService;

    @GetMapping("login")
    public String login(@RequestParam String username,
                        @RequestParam String password){
        //业务处理登录
        System.out.println("业务处理登录完成.........");
        //1、账户服务自动签到加积分
        accountService.addAccountScore(username);
        //2、优惠服务随机发放优惠券
        couponService.sendCoupon(username);
        //3、系统服务登记用户登录信息
        systemService.recordLog(username, password);
        return username + "登录成功";
    }
}

测试事件开发.png
测试事件开发01.png

使用事件机制

创建实体类UserEntity

@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserEntity {
    private String username;
    private String password;
}

创建事件LoginSuccessEvent,继承ApplicationEvent

package com.louis.event;

import com.louis.entity.UserEntity;
import org.springframework.context.ApplicationEvent;

import java.awt.desktop.AppEvent;

/**
 * @author XRY   登录成功事件, 所有事件都推荐继承ApplicationEvent
 * @date 2023年07月14日19:19
 */

//登录成功事件
public class LoginSuccessEvent extends ApplicationEvent {
    /**
     * @param source 代表谁登录成功了
     */
    public LoginSuccessEvent(UserEntity source) {
        super(source);
    }
}

创建事件发送类 EventPublisher

package com.louis.event;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;

/**
 * @author XRY
 * @date 2023年07月14日19:18
 */
@Service
public class EventPublisher implements ApplicationEventPublisherAware {

    /**
     * 底层发送事件的组件,SpringBoot会通过ApplicationEventPublisherAware接口自动注入给我们
     */
    ApplicationEventPublisher applicationEventPublisher;
    /**
     * 所有事件都可以发
     * @param event
     */
    public void sendEvent(ApplicationEvent event){
        //用底层API发送事件
        applicationEventPublisher.publishEvent(event);
    }


    /**
     * 会被自动调用,把真正发事件的底层组件注入进来
     * @param applicationEventPublisher
     */
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
}

控制器LoginController

@RestController
public class LoginController {

    //事件
    @Autowired
    EventPublisher eventPublisher;

    @GetMapping("login")
    public String login(@RequestParam String username,
                        @RequestParam String password){
        //业务处理登录
        System.out.println("业务处理登录完成.........");

        //发送事件
        //1、创建事件信息
        LoginSuccessEvent event = new LoginSuccessEvent(new UserEntity(username, password));
        //2、发送事件
        eventPublisher.sendEvent(event);
        return username + "登录成功";
    }
}

事件机制01.png
事件机制02.png

自动配置原理

入门理解

应用关注的三大核心:场景、配置、组件

1、 自动配置流程

自动配置流程.png

①、导入starter
②、依赖导入autoconfigure
③、寻找类路径下META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.import文件
④、启动,加载所有自动配置类-xxxAutoConfiguration
i、给容器种配置功能组件
ii、组件参数绑定到属性类中。xxxProperties
iii、属性类和配置文件前缀项绑定
iV、@Conditional派生的条件注解进行判断是否组件生效
⑤、效果:
i、修改配置文件、修改底层参数
ii、所有场景自动配置好直接使用
iii、可以注入SpringBoot配置好的组件随时使用。

2、SPI机制

SPI 全称是 Service Provider Interface,是一种 JDK 内置的动态加载实现扩展点的机制,通过 SPI 技术我们可以动态获取接口的实现类,不用自己来创建。这个不是什么特别的技术,只是 一种设计理念。它实际上是基于接口的编程+策略模式+配置文件组合实现的动态加载机制。

image.png
系统设计的各个抽象,往往有很多不同的实现方案,在面向对象的设计里,一般推荐模块之间基于接口编程,模块之间不对实现类进行硬编码。一旦代码里涉及具体的实现类,就违反了可拔插的原则,如果需要替换一种实现,就需要修改代码。为了实现在模块装配的时候能不在程序里动态指明,这就需要一种服务发现机制。Java SPI就是提供这样的一个机制:为某个接口寻找服务实现的机制。有点类似IOC的思想,就是将装配的控制权移到程序之外,在模块化设计中这个机制尤其重要。所以SPI的核心思想就是解耦。

3、功能开关
  • 自动配置:全部都配置好,什么都不用管,自动批量导入。

    项目启动,spi文件中指定的所有都加载

  • @Enablexxx:手动控制哪些功能的开启,手动导入。

    开启xxx功能,都是利用@Import把此功能要用的组件导入进去。

进阶理解

@SpringBootApplication是以下三个注解的复合注解:
①、@SpringBootConfiguration:就是@Configuration,容器中的组件,配置类。Spring ioc启动就会加载创建这个类对象。
②、@EnableAutoConfiguration:开启自动配置,由如下两注解复合:

  • @AutoConfigurationPackage

扫描主程序包。利用@Import(AutoConfigurationPackages.Registrar.class)加载自己想要给容器中导入的组件。把主程序所在包的所有组件导入进来。即只扫描主程序及主程序所在的包及其子包。

  • @Import(AutoConfigurationImportSelector.class)

加载所有自动配置类,加载starter导入组件List configurations = ImportCandidates.load(AutoConfiguration.class,getBeanClassLoader()).getCandidates();
扫描SPI文件:“META-INF/spring/org.springframework.boot.autoconfigure.Autoconfiguration.imports”
③、@ComponentScan
组件扫描,排除一些组件,排除前面已经扫描进来的配置类和自动配置类。

自定义starter

场景:抽取聊天机器人场景,它可以打招呼。
效果:任何项目导入此starter都具有打招呼功能,并且问候语中的人名需要可以在配置文件中修改。

实现步骤

①、创建自定义starter项目,引入spring-boot-starter基础依赖
②、编写模块功能,引入模块所有需要的依赖,编写xxxAutoConfiguration自动配置类
③、编写配置文件META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports指定启动需要加载的自动配置。
④、其他下项目引入即可使用。

通用业务代码

小技巧:可以导入如下依赖重启项目,再写配置文件会有提示。

<!--导入配置处理器,自定义的properties配置文件会有提示-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
配置类
@ConfigurationProperties(prefix = "robot")
@Component
@Data
public class RobotProperties {
    private String name;
    private String email;
    private Integer age;
}

配置文件

robot.name=张三
robot.age=23
robot.email=louis@qq.com

通用功能

@Service
public class RobotService {
    @Autowired
    RobotProperties robotProperties;
    public String sayHello(){
        return "你好:" + robotProperties.getName() + "   ;年龄:" + robotProperties.getAge();
    }
}

控制器

@RestController
public class RobotController {
    @Autowired
    RobotService robotService;

    @GetMapping("/robot/hello")
    public String sayHello(){
        return robotService.sayHello();
    }
}

代码.png

基本抽取(新建模块)

新建模块时不需要选择任何场景。

复制公共功能

抽取.png

根据公共功能,添加场景

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<!--导入配置处理器,自定义的properties配置文件会有提示-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

删除主类

删除主类.png

在需要引用项目下导入该starter

<!--自定义的starter-->
<dependency>
    <groupId>com.louis</groupId>
    <artifactId>boot3-robot-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

在starter下编写配置类

原因:SpringBoot项目只能扫描主程序以及主程序所在的子包,当导入自定义的starter时,不属于这一层级。

@Configuration
@Import({RobotController.class, RobotService.class, RobotProperties.class})
public class RobotAutoConfiguration {

}

在主程序导入配置类

boot3-07.png

@SpringBootApplication
@Import(RobotAutoConfiguration.class)
public class Boot307Application {

    public static void main(String[] args) {
        SpringApplication.run(Boot307Application.class, args);
    }

}

引入starter不会读取starter本身的配置。

编写application.properties

robot.name=louie
robot.age=23
robot.email=louis@qq.com

测试

基本抽取.png
总结:

a、创建starter,将公共代码所需的所有依赖导入
b、将公共代码复制到starter
c、自己写一个RobotAutoConfiguration,该容器中导入需要组件(主程序扫描规则)
d、测试功能

使用Enable机制

原因:在导入starter的时候,使用者可能不知道需要导入哪些相关的文件。

在我们的starter编写注解

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({RobotAutoConfiguration.class})
public @interface EnableRobot {
}

在主程序中使用@EnableRobot注解
@SpringBootApplication
@EnableRobot
public class Boot307Application {

    public static void main(String[] args) {
        SpringApplication.run(Boot307Application.class, args);
    }

}

测试

基本抽取.png
总结:

别人引入starter需要使用@EnableRobot开启功能

完全自动

依赖SpringBoot的SPI机制"META-INF/spring/org.springframework.boot.autoconfigure.Autoconfiguration.imports"在其中放置RobotAutoConfiguration配置类的全类名。如:com.louis.starter.robot.config.RobotAutoConfiguration
import文件.png只需要导入starter,不用加任何注解。

测试

import配置后.png

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

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

相关文章

接口测试:轻松掌握基础知识,快速提升测试技能!

1.client端和server端 开始接口测试之前&#xff0c;首先搞清楚client端与server端是什么&#xff0c;区别。 web前端&#xff0c;顾名思义&#xff0c;指用户可以直观操作和看到的界面&#xff0c;包括web页面的结构&#xff0c;web的外观视觉表现及web层面的交互实现。 web后…

Python---函数的参数类型

位置参数 理论上&#xff0c;在函数定义时&#xff0c;我们可以为其定义多个参数。但是在函数调用时&#xff0c;我们也应该传递多个参数&#xff0c;正常情况&#xff0c;其要一一对应。 相关链接&#xff1a;Python---函数的作用&#xff0c;定义&#xff0c;使用步骤&…

jQuery 第十一章(表单验证插件推荐)

文章目录 前言jValidateZebra FormjQuery.validValValidityValidForm BuilderForm ValidatorProgressionformvalidationjQuery Validation PluginjQuery Validation EnginejQuery ValidateValidarium后言 前言 hello world欢迎来到前端的新世界 &#x1f61c;当前文章系列专栏&…

单链表的反转?太细了哥们!细到离谱!

单链表的反转&#xff08;面试常出&#xff09;&#xff1a; ​ 单链表的反转&#xff0c;可以通过很多种方法实现。包括迭代法&#xff0c;递归法&#xff0c; 迭代法&#xff1a; 定义三个指针&#xff1a;prev、current和next&#xff0c;它们分别表示前一个节点、当前节点…

Excel动态选择某一行/列的最后一个数据

选择列的最后一个数据&#xff1a; 以A列为例&#xff0c;使用&#xff1a; LOOKUP(1,0/(A:A<>""),A:A)选择行的最后一个数据&#xff1a; 以第3行为例&#xff0c;使用&#xff1a; LOOKUP(1,0/(3:3<>""),3:3)示例程序 列最后一个数据&a…

IO口速度影响了什么?

我们在初学单片机的时候都知道单片机GPIO的作用是巨大的&#xff0c;在配置GPIO的时候&#xff0c;结构体初始化里有一个选项是配置输入输出速度的&#xff0c;对于这个速度输出是必须要配置的&#xff0c;输入没有明令说明需不需要配置。 这个速度对于学习过32单片机的都应该知…

python——第十三天

uuid 是通用唯一识别码&#xff08;Universally Unique identifier&#xff09;的缩写 UUID是一个128比特的数值 uuid模块&#xff1a; 获取一个128位&#xff08;比特&#xff09;的永不重复的数字&#xff0c;当然我们使用的时候会转换为32个的字符串 impor uuud uui…

js粒子效果(二)

效果: 代码: <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>Particle Animation</title><…

C#,《小白学程序》第七课:列表(List)其一,编制《高铁车次信息表》

1 文本格式 /// <summary> /// 车站信息类 class /// </summary> public class Station { /// <summary> /// 编号 /// </summary> public int Id { get; set; } 0; /// <summary> /// 车站名 /// </summary>…

【算法专题】滑动窗口—无重复字符的最长子串

力扣题目链接&#xff1a;无重复字符的最长子串 一、题目解析 二、算法原理 解法一&#xff1a;暴力解法&#xff08;时间复杂度最坏&#xff1a;O(N)&#xff09; 从每一个位置开始往后枚举&#xff0c;在往后寻找无重复最长子串时&#xff0c;可以利用哈希表来统计字符出现…

2023年【汽车驾驶员(中级)】最新解析及汽车驾驶员(中级)试题及解析

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 2023年汽车驾驶员&#xff08;中级&#xff09;最新解析为正在备考汽车驾驶员&#xff08;中级&#xff09;操作证的学员准备的理论考试专题&#xff0c;每个月更新的汽车驾驶员&#xff08;中级&#xff09;试题及解…

vue3 for循环创建的多个e-form 添加校验

v-for 创建 ref <el-form :model"item" :rules"state.rules" :ref"el > getRiskSpreadRef(el, index)" ></el-form>// 定义ref list const riskSpreadRefList ref<HTMLElement[]>([]);// ref存到数组 const getRiskSpread…

Error running Tomcat8: Address localhost:1099 is already in use 错误解决

摘要: 有时候运行web项目的时候会遇到 Error running Tomcat8: Address localhost:1099 is already in use 的错误&#xff0c;导致web项目无法运行。这篇 blog 介绍了解决办法。 有时候运行web项目的时候会遇到 Error running Tomcat8: Address localhost:1099 is already in …

C语言贪吃蛇(有详细注释)

这个贪吃蛇是在比特特训营里学到的&#xff0c;同时我还写了用EasyX图形库实现的图形化贪吃蛇&#xff0c;含有每个函数的实现以及游戏中各种细节的讲解&#xff0c;感兴趣的可以去看一看。 贪吃蛇小游戏 实现效果 以下就是源码&#xff0c;感兴趣的小伙伴可以cv自己玩一玩改…

vatee万腾的科技征途:Vatee独特探索的数字化力量

在数字化时代的浪潮中&#xff0c;Vatee万腾以其独特的科技征途成为引领者。公司在数字化领域的探索之路不仅是技术的创新&#xff0c;更是一种对未知的勇敢涉足&#xff0c;是对新时代的深刻洞察和积极实践。 Vatee万腾通过独特的探索&#xff0c;展示了在数字化征途上的创新力…

分享11款原型图软件,让你的创意无限发挥!

即时设计 即时设计是一个集设计、原型、开发于一身的一站式在线设计工具&#xff0c;也是一个可以云端编辑、团队写作的在线原型网站。 即时设计 - 可实时协作的专业 UI 设计工具即时设计是一款支持在线协作的专业级 UI 设计工具&#xff0c;支持 Sketch、Figma、XD 格式导入&…

为什么说赤霞珠是葡萄酒中的明星?

种植酿酒葡萄是一项艰难的事业&#xff0c;它的成功取决于许多不同的因素。土壤和气候是最关键的因素&#xff0c;它们决定了哪些酿酒葡萄可以在哪个地区培育。来自云仓酒庄品牌雷盛红酒分享但是有些酿酒葡萄品种适应性很强&#xff0c;几乎可以在任何地方生长&#xff0c;其中…

Interactive Visual Data Analysis

Words&Contents Home | Interactive Visual Data Analysis Book Outline 这本书对视觉、互动和分析方法进行了系统而全面的概述&#xff0c;作为数据可视化方面比较好的读物&#xff1b; 目录 Words&Contents Book Outline &#xff08;一&#xff09;Introduct…

智慧城市运营管理平台解决方案:PPT全文61页,附下载

关键词&#xff1a;智慧城市建设方案&#xff0c;智慧城市解决方案&#xff0c;智慧城市的发展前景和趋势&#xff0c;智慧城市建设内容&#xff0c;智慧城市运营管理平台 一、智慧城市运营平台建设背景 随着城市化进程的加速&#xff0c;城市面临着诸多挑战&#xff0c;如环…

(Matalb分类预测)GA-BP遗传算法优化BP神经网络的多维分类预测

目录 一、程序及算法内容介绍&#xff1a; 基本内容&#xff1a; 亮点与优势&#xff1a; 二、实际运行效果&#xff1a; 三、部分代码&#xff1a; 四、本文代码数据说明手册分享 一、程序及算法内容介绍&#xff1a; 基本内容&#xff1a; 本代码基于Matalb平台编译&am…