SpringBoot事件发布和监听,ApplicationEventPublisher发布事件,实现ApplicationListener<>监听事件

1.背景

观察者模式:当一个对象的状态发生改变的时候,所有依赖于它的对象都会得到通知,比如ApplicationListener

所以,我们可以用这个来做日志,或者其他事情,

2.创建监听器实现ApplicationListener<>接口

package com.example.listener;

import com.example.dto.SystemAccessEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component

public class EventListener implements ApplicationListener<SystemAccessEvent> {
    @Override
    public void onApplicationEvent(SystemAccessEvent event) {
        //完成消息接收
        System.out.println("Received event: " + event.getMessage());
    }
}

3.创建被监听的实体类

package com.example.dto;

import lombok.Builder;
import lombok.Data;
import org.springframework.context.ApplicationEvent;

@Data
@Builder
public class SystemAccessEvent extends ApplicationEvent {
    private String message;

    public SystemAccessEvent(Object source) {
        super(source);
    }
}

 必须要继承ApplicationEvent类

 4.发送事件通知

package com.example;

import com.example.dto.SystemAccessEvent;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;

@SpringBootTest
class ApplicationTests {
    @Autowired
    ApplicationEventPublisher eventPublisher;
    @Autowired
    ApplicationContext applicationContext;

    @Test
    public void publish() {
        System.out.println("Published message: ");
        SystemAccessEvent systemAccessEvent = new SystemAccessEvent(this);
        systemAccessEvent.setMessage("Hello World!");
        eventPublisher.publishEvent(systemAccessEvent);
    }

}

  • 30
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值