1. Spring built-in event What?
- Spring events is a subclass of class ApplicationEvent, sent by the realization ApplicationEventPublisherAware interface class that implements the class monitor ApplicationListener interface.
- Spring has defined a set of built of events issued by the ApplicationContext container. (ContextRefreshedEvent, ContextStartedEvent, ContextStoppedEvent, ContextClosedEvent, RequestHandledEvent)
- To listen ApplicationContext event listener class should implement the interface and override ApplicationListener onApplicationEvent () method.
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. how to use custom events?
- Create an event class - Extended ApplicationEvent class, create event class.
import org.springframework.context.ApplicationEvent;
/*
自定义事件
*/
public class CustomEvent extends ApplicationEvent {
public CustomEvent(Object source) {
super(source);
}
public String toString(){
return "My Custom Event";
}
}
- Create a send class - Send the class instance get ApplicationEventPublisher send events.
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");
}
}
- Create a listener class - ApplicationListener implement the interface, create a listener class.
import org.springframework.context.ApplicationListener;
public class CustomEventHandler implements ApplicationListener<CustomEvent> {
@Override
public void onApplicationEvent(CustomEvent customEvent) {
System.out.println("处理了"+customEvent.toString());
}
}