應用事件的觀察者模式,可以實作異步,功能解耦的目的,下面簡要說下spring中本地事件ApplicationEvent的用法。話不多說,直接上代碼:
定義一個Event,如下定義了一個新增事件,可以如法炮制定義别的事件
package com.example.event;
import org.springframework.context.ApplicationEvent;
public class AddEvent extends ApplicationEvent {
private static final Long serialVersionUID = 1l;
// 定義資訊
private String message;
// 繼承重寫構造方法
public AddEvent(Object source,String message) {
super(source);
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
- 定義一個Listener,可以用EventListener注解來表示事件的處理操作:
package com.example.event;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class DemoListener{
// 對消息進行處理
@EventListener
public void handleDemo(DemoEvent demoEvent) {
String message = demoEvent.getMessage();
System.out.println(message+" 已接受的資訊Demo");
}
@EventListener
public void handleAdd(AddEvent demoEvent) {
String message = demoEvent.getMessage();
System.out.println(message+" 已接受的資訊Add");
}
@EventListener
public void handleDelete(DeleteEvent demoEvent) {
String message = demoEvent.getMessage();
System.out.println(message+" 已接受的資訊Delete");
}
@EventListener
public void handleUpdate(UpdateEvent demoEvent) {
String message = demoEvent.getMessage();
System.out.println(message+" 已接受的資訊Update");
}
}
3.釋出事件:
package com.example.event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
public class DemoPublisher {
@Autowired
private ApplicationContext applicationContext;
public void publish(String message){
applicationContext.publishEvent(new DemoEvent(this,message));
}
public void publishAdd(String message){
applicationContext.publishEvent(new AddEvent(this,message));
}
public void publishDelete(String message){
applicationContext.publishEvent(new DeleteEvent(this,message));
}
public void publishUpdate(String message){
applicationContext.publishEvent(new UpdateEvent(this,message));
}
}
- 測試:
package com.example.demo;
import com.example.event.DemoPublisher;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationEvent {
@Resource
private DemoPublisher demoPublisher;
@Test
public void event(){
demoPublisher.publish("你好嗎");
}
@Test
public void event1(){
demoPublisher.publishAdd("增加事件");
}
@Test
public void event2(){
demoPublisher.publishDelete("删除事件");
}
@Test
public void event3(){
demoPublisher.publishUpdate("更新事件");
}
}
測試結果如下: