Spring中的ApplicationEvent與ApplicationListener在項目上的應用
描述:
ApplicationContext事件機制是觀察者設計模式來實現的,通過ApplicationEvent類和ApplicationListener接口,可以實現ApplicationContext事件處理。
使用:
功能上的使用類似發佈和訂閱這種模式
使用步驟:
1、建立event 繼承 ApplicationEvent
/**
* 1、建立event
*
* @author liyue
* @date 2020-03-26 19:01
*/
public class BookingCreatedEvent extends ApplicationEvent {
private Booking booking;
private Action action;
public enum Action {
/**
* 增加方法
*/
ADD,
/**
* 修改方法
*/
MODIFY,
/**
* 刪除方法
*/
DELETE;
}
public BookingCreatedEvent(Object source) {
super(source);
}
public BookingCreatedEvent(Object source, Booking booking, Action action) {
super(source);
this.source = source;
this.booking = booking;
this.action = action;
}
public Booking getBooking() {
return booking;
}
public void setBooking(Booking booking) {
this.booking = booking;
}
public Action getAction() {
return action;
}
public void setAction(Action action) {
this.action = action;
}
}
2、建立listener 監聽 需要實現 ApplicationListener
/**
* 2、建立ApplicationEvent
*
* @author liyue
* @date 2020-03-26 19:05
*/
@Component
public class BookingEventsListener implements ApplicationListener<BookingCreatedEvent> {
@Override
public void onApplicationEvent(BookingCreatedEvent bookingCreatedEvent) {
System.out.println(">>>>>>進入BookingEventsListener監聽方法了>>>>>>");
switch (bookingCreatedEvent.getAction()) {
case ADD:
System.out.println(">>>>>>增加成功>>>>>>");
return;
case DELETE:
System.out.println(">>>>>>刪除成功>>>>>>");
return;
case MODIFY:
System.out.println(">>>>>>修改成功>>>>>>");
return;
default:
return;
}
}
}
3、觸發邏輯
/**
* BookingService 服務類 注意這裏要實現 ApplicationContextAware
*
* @author liyue
* @date 2020-03-26 19:12
*/
@Service
public class BookingServiceImpl implements IBookingService {
@Resource
private ApplicationContext publisher;
@Override
public void saveBooing(Booking booking) {
System.out.println(">>>>>開始進行保存Booking操作>>>>>>");
BookingCreatedEvent bookingCreatedEvent = new BookingCreatedEvent(this, booking, BookingCreatedEvent.Action.DELETE);
//觸發
this.publisher.publishEvent(bookingCreatedEvent);
return;
}
}
注意:BookingEventsListener在使用的時候,如使用ssm這種框架搭建的項目,一定要能被Spring Bean能掃描到。
4、測試結果
@Test
public void test() throws InterruptedException {
Booking booking = new Booking();
booking.setId("test");
booking.setName("test");
booking.setPassword("test");
booking.setRealName("test");
bookingService.saveBooing(booking);
}