创建一个自定义的事件
public class MyApplicationEvent extends ApplicationEvent {
String username;
String email;
public MyApplicationEvent(Object source) {
super(source);
}
public MyApplicationEvent(Object source, String username, String email) {
super(source);
this.username = username;
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
事件的监听
package com.video.spring;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {
@Override // 事件的回调方法
public void onApplicationEvent(ApplicationEvent event) {
//spring的事件
System.out.println("接收到的事件:" + event);
//我们定义的事件
if (event instanceof MyApplicationEvent) {
MyApplicationEvent myApplicationEvent = (MyApplicationEvent) event;
System.out.println("用户:" + myApplicationEvent.getUsername());
System.out.println("邮箱:" + myApplicationEvent.getEmail());
}
}
}
在spring中注册监听器
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--在spring容器中注册监听器 -->
<bean id="Listener" class="com.video.spring.MyApplicationListener"></bean>
</beans>
发送消息
public class Demo02 {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring3.xml");
// 创建事件
MyApplicationEvent event = new MyApplicationEvent("事件内容", "james", "123@qq.com");
//发送消息
context.publishEvent(event);
context.close();
}
}
控制台打印
网友评论