0
点赞
收藏
分享

微信扫一扫

Spring的事件-代码记录


首先有一个具体的事件

package com.alibaba.demo.event;

import org.springframework.context.ApplicationEvent;

public class HelloEvent extends ApplicationEvent {

private String name;

public HelloEvent(Object source, String name) {
super(source);
this.name = name;
}

public String getName() {
return name;
}
}

第二步,记录一下由谁来接手这个事件

package com.alibaba.demo.event;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class HelloEventListener implements ApplicationListener<HelloEvent> {

private static final Logger logger = LoggerFactory.getLogger(HelloEventListener.class);

@Override
public void onApplicationEvent(HelloEvent event) {
logger.info("receive {} say hello!",event.getName());
}
}

第三步,把事件发送出去

package com.alibaba.demo.event;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
* @program: parent_pro
* @description:
* @author: 渭水
* @create: 2021/06/23
*/

public class Application {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(BeanConfig.class);

HelloEvent event = new HelloEvent("abc","weishui");
ctx.publishEvent(event);


}
}

以上为Spring4.2之前的事件分发处理过程,这里面有一些问题要注意

  1. 具体的事件必须继承自ApplicationEvent
  2. 事件的处理类必须继承ApplicationListener<T>,每一种事件处理逻辑都得有一个类。

在Spring4.2之后上面两点有了改变

以下,一个新的具体事件,没有继承任何类

package com.alibaba.demo.event;

public class EmailEvent {

private String name;
private String address;

public EmailEvent(Object source, String name,String address) {
this.name = name;
this.address= address;
}

public String getAddress() {
return address;
}

public String getName() {
return name;
}
}

事件的处理逻辑如下:

package com.alibaba.demo.event;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
* @program: parent_pro
* @description:
* @author: 渭水
* @create: 2021/06/23
*/
@Component
public class AnnotationEventListener {

private static final Logger logger = LoggerFactory.getLogger(AnnotationEventListener.class);

@EventListener
public void on(EmailEvent emailEvent){
logger.info("finished emailevent {}",emailEvent.getName());
}
}

在具体的处理逻辑方法上加上@EventListener注解即可,方法的参数指明了这个方法具体处理的是那种事件。

上面的事件 监听都是同步的



关于SimpleApplicationEventMulticaster

​​Spring5源码 - 12 Spring事件监听机制_异步事件监听应用及源码解析【附源码】_小小工匠_51CTO博客​​

举报

相关推荐

0 条评论