1 Spring事件簡介
當Spring
的事件(Application Event
)為Bean
和Bean
之間的消息同學提供了支持。當一個Bean
處理完成一個任務之后,希望另外一個Bean
知道並能做相應的處理,這時我們就需要讓另外一個Bean
監聽當前Bean
所發生的事件
Spring
的事件需要遵循如下流程:
- 自定義事件,繼承
ApplicationEvent
- 定義事件監聽器,實現
ApplicationListener
- 使用容器發布事件
2 Demo示例
2.1 pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.jzh</groupId>
<artifactId>TestDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.9.RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
2.2 自定義事件
package cn.jzh.event;
import org.springframework.context.ApplicationEvent;
/**
* 自定義的spring事件
*/
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;
}
}
2.3 事件監聽器
package cn.jzh.event;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
/**
* 監聽事件的實現類
*/
@Component
public class DemoListener implements ApplicationListener<DemoEvent> {//實現ApplicationListener接口,並指定監聽的事件類型
@Override
public void onApplicationEvent(DemoEvent event) {//使用onApplicationEvent方法對消息進行接受處理
String msg = event.getMsg();
System.out.println("DemoListener獲取到了監聽消息:"+msg);
}
}
2.4 事件發布類
package cn.jzh.event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
/**
* 發布事件
*/
@Component
public class DemoPublisher {
@Autowired
private ApplicationContext applicationContext;//注入ApplicationContext用來發布事件
public void publish(String msg){
applicationContext.publishEvent(new DemoEvent(this,msg));//使用ApplicationContext對象的publishEvent發布事件
}
}
2.5 配置類
配置類中沒有具體的代碼邏輯注意作用是為了能掃描到相應的使用注解的類
package cn.jzh.event;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Configuration
@ComponentScan("cn.jzh.event")
public class EventConfig {
}
2.6 啟動測試
package cn.jzh.event;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
public static void main(String[] args) {
//使用AnnotationConfigApplicationContext讀取配置EventConfig類,EventConfig類讀取了使用注解的地方
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);
DemoPublisher publish = context.getBean(DemoPublisher.class);
publish.publish("你好");
context.close();
}
}