public abstract class ApplicationEvent extends EventObject
/**
* Create a new ApplicationEvent.
* @param source the object on which the event initially occurred (never @code null)
*/
public ApplicationEvent(Object source)
super(source);
this.timestamp = System.currentTimeMillis();
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener
void onApplicationEvent(E var1);
实现Spring事件监听有两种方式:
面向接口编程,实现ApplicationListener接口;
基于注解驱动,@EventListener(Spring自定义的注解);
实例:
面向接口编程,实现ApplicationListener接口:
自定义事件对象:
public class MyApplicationEvent extends ApplicationEvent
public MyApplicationEvent(Object source)
super(source);
自定义事件监听器:
public class MyApplicationListener implements ApplicationListener<MyApplicationEvent>
@Override
public void onApplicationEvent(MyApplicationEvent event)
System.out.println("收到事件:" + event);
启动服务并发布事件:
public class ApplicationEventBootstrap
public static void main(String[] args)
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
// 注册自定义事件监听器
context.addApplicationListener(new MyApplicationListener());
// 启动上下文
context.refresh();
// 发布事件,事件源为Context
context.publishEvent(new MyApplicationEvent(context));
// 结束
context.close();
运行结果:
收到事件:com.xx.MyApplicationEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@cb0ed20, started on Sat May 16 16:32:04 CST 2020]
使用注解 @EventListener实现Spring事件监听:
@Component
public class MyApplicationListener2
@EventListener(MyApplicationEvent.class)
public void onEvent(MyApplicationEvent event)
System.out.println("收到事件:" + event);
启动并发布事件:
public class ApplicationEventBootstrap
public static void main(String[] args)
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
// 注册自定义事件监听器
context.register(MyApplicationListener2.class);
// 启动上下文
context.refresh();
// 发布事件,事件源为Context
context.publishEvent(new MyApplicationEvent(context));
// 结束
context.close();
运行结果:
收到事件:com.xx.MyApplicationEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@cb0ed20, started on Sat May 16 16:32:04 CST 2020]
通过实例可以看出,上面两种方式都可正常发布和接收事件。
实现原理
通过上面实例可以看出,context 可以发布事件,那底层是怎么发布的,让我们继续看源码:
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext
protected void publishEvent(Object event, @Nullable ResolvableType eventType)
...
getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
...