Spring 监听机制的使用
1.事件1
public class EmailEvent extends ApplicationEvent {
private String address;
private String text;
public EmailEvent(Object source,String address, String text) {
super(source);
this.address = address;
this.text = text;
}
public EmailEvent(Object source) {
super(source);
}
public String getAddress() {
return address;
}
public String getText() {
return text;
}
}
2.事件2
public class PhoneEvent extends ApplicationEvent {
private String number;
private String text;
public PhoneEvent(Object source, String number, String text) {
super(source);
this.number = number;
this.text = text;
}
public PhoneEvent(Object source) {
super(source);
}
public String getNumber() {
return number;
}
public String getText() {
return text;
}
}
3.监听器1(EmailEvent专属监听器)
@Component
public class EmailNotifierListener implements ApplicationListener<EmailEvent> {
@Override
public void onApplicationEvent(EmailEvent event) {
System.out.println("11Address: " + event.getAddress());
System.out.println("11Text: " + event.getText());
}
}
4.监听器2(所有事件都会监听)
@Component
public class EventListener implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent event) {
if(event instanceof EmailEvent){
EmailEvent emailEvent = (EmailEvent) event;
System.out.println("Address: " + emailEvent.getAddress());
System.out.println("Text: " + emailEvent.getText());
}else if(event instanceof PhoneEvent){
PhoneEvent phoneEvent = (PhoneEvent) event;
System.out.println("Number: " + phoneEvent.getNumber());
System.out.println("Text: " + phoneEvent.getText());
}
}
}
5.发送事件
@SpringBootApplication
public class DemoeventApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(DemoeventApplication.class, args);
context.publishEvent(new EmailEvent("hello","hello", "这是email事件"));
context.publishEvent(new PhoneEvent("hello1","123456", "这是phone事件"));
}
}
结果:EmailEvent会被监听器1和监听器2都监听,PhoneEvent只会被监听器2监听

浙公网安备 33010602011771号