1. 봄에 내장 된 사건은 무엇?
- 봄 이벤트 클래스 모니터 만약 ApplicationListener 인터페이스를 구현 실현 ApplicationEventPublisherAware 인터페이스 클래스에서 보낸 클래스가 ApplicationEvent의 서브 클래스입니다.
- ApplicationContext에 컨테이너에 의해 발행 된 이벤트의 내장의 봄 세트를 정의하고있다. (ContextRefreshedEvent, ContextStartedEvent, ContextStoppedEvent, ContextClosedEvent, RequestHandledEvent)
- 인터페이스를 구현하고 만약 ApplicationListener onApplicationEvent () 메소드를 오버라이드 (override)의 ApplicationContext 이벤트 리스너 클래스를 들으려면.
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());
}
}