1. Spring内置的事件有哪些?
- Spring中的事件是一个 ApplicationEvent类的子类,由实现 ApplicationEventPublisherAware 接口的类发送,实现 ApplicationListener 接口的类监听。
- Spring中已经定义了一组内置事件,这些事件由ApplicationContext容器发出。(ContextRefreshedEvent、ContextStartedEvent、ContextStoppedEvent、ContextClosedEvent、RequestHandledEvent)
- 要监听ApplicationContext事件,监听类应该实现ApplicationListener接口并重写onApplicationEvent()方法。
package tutorialspointEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;
public class CStartEventHandler implements ApplicationListener<ContextStartedEvent> {
@Override
public void onApplicationEvent(ContextStartedEvent contextStartedEvent) {
System.out.println("ContextStartedEvent收到了");
}
}
2. 怎么使用自定义事件?
- 创建事件类 – 扩展ApplicationEvent类,创建事件类。
import org.springframework.context.ApplicationEvent;
/*
自定义事件
*/
public class CustomEvent extends ApplicationEvent {
public CustomEvent(Object source) {
super(source);
}
public String toString(){
return "My Custom Event";
}
}
- 创建发送类 – 发送类获取ApplicationEventPublisher实例发送事件。
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
/*
事件发布者
*/
public class CustomEventPublisher implements ApplicationEventPublisherAware {
private ApplicationEventPublisher publisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}
public void publish() {
CustomEvent ce = new CustomEvent(this);
publisher.publishEvent(ce);
System.out.println("发布了一个"+"CustomEvent");
}
}
- 创建监听类 – 实现ApplicationListener接口,创建监听类。
import org.springframework.context.ApplicationListener;
public class CustomEventHandler implements ApplicationListener<CustomEvent> {
@Override
public void onApplicationEvent(CustomEvent customEvent) {
System.out.println("处理了"+customEvent.toString());
}
}