情景:利用jpush推送给客户端订单确认收货时的通知:
一:创建要被监听的事件对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
/** * @describe: 订单确认收货事件 * author: liutengyuan * @date: Created in 2019/1/18 18:23 **/ public class OrderConfirmReceieveEvent extends ApplicationEvent { public OrderConfirmReceieveEvent(Object source) { super(source); } private long orderId; private long userId; private String content; public long getOrderId() { return orderId; } public void setOrderId(long orderId) { this.orderId = orderId; } public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } |
二:创建监听器,监控事件对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
/** * @describe: 监听器 * author: liutengyuan * @date: Created in 2019/1/18 18:26 **/ @Component public class OrderConfrimReceieveListener implements ApplicationListener<OrderConfirmReceieveEvent> { private Logger logger = LoggerFactory.getLogger(OrderConfrimReceieveListener.class); @Autowired JpushService jpushService; @Override public void onApplicationEvent(OrderConfirmReceieveEvent event) { System.out.println("订单确认收货监听事件。。。"); logger.info("订单确认收货监听事件执行"); jpushService.sendWaitRefundOrSuccessMsgToUser(event.getOrderId(),event.getUserId(), ORDER_FINISHED, event.getContent()); } } |
三:业务代码中调用
1 2 3 4 5 6 |
OrderConfirmReceieveEvent event = new OrderConfirmReceieveEvent(""); ApplicationContext applicationContext = SpringBeanContextUtil.getApplicationContext(); event.setOrderId(orderId); event.setUserId(orderInfo.getUserId()); event.setContent(content); applicationContext.publishEvent(event); |
其他:也可以监听一些类似Spring容器启动等事件
1 2 3 4 5 6 7 8 9 10 11 12 |
/** * @describe: Spring容器监听功能 * author: liutengyuan * @date: Created in 2019/1/21 14:05 **/ @Component public class StartUpListerner implements ApplicationListener<ContextStartedEvent> { @Override public void onApplicationEvent(ContextStartedEvent event) { System.out.println("spring 容器初始化...."); } } |
转自:https://blog.csdn.net/liutengyuan/article/details/86573547