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);
}