首先有一个具体的事件
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之前的事件分发处理过程,这里面有一些问题要注意
- 具体的事件必须继承自ApplicationEvent
- 事件的处理类必须继承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注解即可,方法的参数指明了这个方法具体处理的是那种事件。
上面的事件 监听都是同步的
如果想要变成异步的,可以参考
Spring 中的事件机制 - rickiyang - 博客园
关于SimpleApplicationEventMulticaster