[SpringBoot] Spring的事件机制

直接上代码:

一.定义事件

public class MyEvent extends ApplicationEvent {
    private String msg;
    
    public MyEvent(Object source, String msg) {
        super(source);
        this.msg = msg;
    }
    public String getMsg() { return msg;   }
}
PS:继承ApplicationEvent 

二.定义监听者

@Component
public class MyListener implements ApplicationListener<MyEvent> {
    @Override
    public void onApplicationEvent(MyEvent myEvent) {
       //监听后的逻辑,这里简单打印
        String msg = myEvent.getMsg();
        System.out.println("MyListener接收到了MyPublisher发布的消息:" + msg);
    }

}
PS:实现ApplicationListener接口,指定事件类型

三.定义发布者

@Component
public class MyPublisher {
    @Autowired
    ApplicationContext context;

    public void published() {
        MyEvent event = new MyEvent(this, "发布成功!");
        System.out.println("发布event:" + event);
        context.publishEvent(event);
    }
}
PS:注入ApplicationContext ,通过ApplicationContext的publisEvent方法发布事件; 

四.发布测试

 
@SpringBootApplication
@RestController
public class SpringDefineConfigApplication {

    @Autowired
    MyPublisher myPublisher;

    public static void main(String[] args) {
        ApplicationContext applicationContext =
                SpringApplication.run(SpringDefineConfigApplication.class, args);
    }

    @GetMapping("/publish")
    public void publish(){
        myPublisher.published();
    }
}
PS:注入事件发布者,只掉调用方法即可发布事件
访问/publish接口即可看到打印如下:
发布event:com.intellif.mozping.event.MyEvent[source=com.intellif.mozping.publisher.MyPublisher@690ac497]
MyListener接收到了MyPublisher发布的消息:发布成功!
上述只是简单的入门示例,可以自行完善满足特定需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值