ApplicationEvent的基本使用
- 自定义事件
package com.xiaohan.event;
import org.springframework.context.ApplicationEvent;
public class DemoEvent extends ApplicationEvent{
private String msg;
public DemoEvent(Object source,String msg) {
super(source);
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
- 事件监听器
package com.xiaohan.event;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
//指定监听的事件类型
@Component
public class DemoListener implements ApplicationListener<DemoEvent> {
// 接收消息 并处理消息
@Override
public void onApplicationEvent(DemoEvent demoEvent) {
String msg = demoEvent.getMsg();
System.err.println(this.getClass().getName() + "监听到了" + demoEvent.getSource().getClass().getName() + "的消息: " + msg);
}
}
- 事件发布类
package com.xiaohan.event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class DemoPublisher {
// 注入Spring容器
@Autowired
private ApplicationContext ac;
public void publish(String msg) {
ac.publishEvent(new DemoEvent(this, msg));
}
}
- 配置类
package com.xiaohan.event;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.xiaohan.event")
public class EventConfig {
}
- Main测试类
package com.xiaohan.event;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
// 事件 ApplicationEvent
public class Main {
public static void main(String[] args) {
ApplicationContext ac = new AnnotationConfigApplicationContext(EventConfig.class);
DemoPublisher demoPublisher = ac.getBean(DemoPublisher.class);
demoPublisher.publish("hello application event");
}
}
输出
com.xiaohan.event.DemoListener监听到了com.xiaohan.event.DemoPublisher的消息: hello application event