EventObject,为JavaSE提供的事件类型基类,任何自定义的事件都继承自该类,例如上图中右侧灰色的各个事件。Spring中提供了该接口的子类ApplicationEvent。
EventListener为JavaSE提供的事件监听者接口,任何自定义的事件监听者都实现了该接口,如上图左侧的各个事件监听者。Spring中提供了该接口的子类ApplicationListener接口。
JavaSE中未提供事件发布者这一角色类,由各个应用程序自行实现事件发布者这一角色。Spring中提供了ApplicationEventPublisherAware接口作为事件发布者。
1、编写事件
public class MyEvent extends ApplicationEvent { /** * */ private static final long serialVersionUID = -1002815320277254124L; private String methodName; public MyEvent(Object source) { super(source); } public MyEvent(Object source, String methodName){ super(source); this.methodName = methodName; } public String getMethodName() { return methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } }
2、编写事件监听者
public class MyEventListener implements ApplicationListener<ApplicationEvent> { @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof MyEvent) { MyEvent event2=(MyEvent) event; System.out.println("执行自定义事件!"+event2.getMethodName()); } } }
3、编写事件发布者
public class MyPublisher implements ApplicationEventPublisherAware { private ApplicationEventPublisher applicationEventPublisher; @Override public void setApplicationEventPublisher( ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher=applicationEventPublisher; } public void methodToMonitor() { applicationEventPublisher.publishEvent(new MyEvent(this, "aaa")); applicationEventPublisher.publishEvent(new MyEvent(this, "bbb")); } }
4、测试
public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml"); MyPublisher myPublisher=applicationContext.getBean("myPublisher",MyPublisher.class); myPublisher.methodToMonitor(); }
输出
执行自定义事件!aaa 执行自定义事件!bbb
时间: 2024-10-09 21:52:19