Spring 官方文檔翻譯以下 :java
ApplicationContext 經過 ApplicationEvent 類和 ApplicationListener 接口進行事件處理。 若是將實現 ApplicationListener 接口的 bean 注入到上下文中,則每次使用 ApplicationContext 發佈 ApplicationEvent 時,都會通知該 bean。 本質上,這是標準的觀察者設計模式。git
Spring的事件(Application Event)其實就是一個觀察者設計模式,一個 Bean 處理完成任務後但願通知其它 Bean 或者說 一個Bean 想觀察監聽另外一個Bean的行爲。github
Spring 事件只須要幾步:spring
代碼示例:設計模式
@Data public class DemoEvent extends ApplicationEvent { private Long id; private String message; public DemoEvent(Object source, Long id, String message) { super(source); this.id = id; this.message = message; } }
@Component public class DemoListener implements ApplicationListener<DemoEvent> { @Override public void onApplicationEvent(DemoEvent demoEvent) { System.out.println(">>>>>>>>>DemoListener>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); System.out.println("收到了:" + demoEvent.getSource() + "消息;時間:" + demoEvent.getTimestamp()); System.out.println("消息:" + demoEvent.getId() + ":" + demoEvent.getMessage()); } }
泛型爲須要監聽的事件類型springboot
@Component public class DemoListener2 { @EventListener public void onApplicationEvent(DemoEvent demoEvent) { System.out.println(">>>>>>>>>DemoListener2>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); System.out.println("收到了:" + demoEvent.getSource() + "消息;時間:" + demoEvent.getTimestamp()); System.out.println("消息:" + demoEvent.getId() + ":" + demoEvent.getMessage()); } }
參數爲須要監聽的事件類型app
@Component public class DemoPublisher { private final ApplicationContext applicationContext; @Autowired public DemoPublisher(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } public void publish(long id, String message) { applicationContext.publishEvent(new DemoEvent(this, id, message)); } }
@Test public void publisherTest() { demoPublisher.publish(1L, "成功了!"); }
>>>>>>>>>DemoListener2>>>>>>>>>>>>>>>>>>>>>>>>>>>> 收到了:com.jiuxian.publisher.DemoPublisher@3a62c01e消息;時間:1551762322376 消息:1:成功了! >>>>>>>>>DemoListener>>>>>>>>>>>>>>>>>>>>>>>>>>>> 收到了:com.jiuxian.publisher.DemoPublisher@3a62c01e消息;時間:1551762322376 消息:1:成功了!
GitHub https://github.com/Zejun-Liu/SpringBoot2.0/tree/master/springboot-eventide