可以监听对象的创建数据。
自定义监听事件可以监听容器变化,同时也能精确定位指定事件对象,我们编写一个案例演示自定义监听事件实现流程。
定义事件监听对象: MessageNotifier
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
/**
* 自定义监听事件
*/
public class MessageEventListener implements ApplicationListener {
//监听触发执行
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
Object source = applicationEvent.getSource();
System.out.println("接受到事件传递的数据:"+source);
System.out.println("事件对象:"+applicationEvent.getClass().getName());
System.out.println("监听到了对应事件!");
}
}
定义事件对象: MessageEvent
import org.springframework.context.ApplicationEvent;
/**
* 定义事件对象
*/
public class MessageEvent extends ApplicationEvent {
private String phone;
private String message;
public MessageEvent(Object source,String phone,String message) {
super(source);
this.phone=phone;
this.message=message;
}
public MessageEvent(Object source) {
super(source);
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
将对象添加到容器中:
<bean id="messageEventListener" class="com.h.spring.MessageEventListener"/>
添加事件测试:
public class SpringContextTest {
public static void main(String[] args) {
ApplicationContext act = new ClassPathXmlApplicationContext("spring-event.xml");
//添加事件测试
MessageEvent messageEvent = new MessageEvent("beijing","13670000000","hello!");
act.publishEvent(messageEvent);
}
}
打印结果
接受到事件传递的数据:org.springframework.context.support.ClassPathXmlApplicationContext@8807e25, started on Mon Dec 07 08:28:11 CST 2020
事件对象:org.springframework.context.event.ContextRefreshedEvent
监听到了对应事件!
接受到事件传递的数据:beijing
事件对象:com.h.spring.MessageEvent
监听到了对应事件!