1. 程式人生 > >第二十九章 SpringBoot自定義事件

第二十九章 SpringBoot自定義事件

SpringBoot自定義事件也是使用同樣的方式。

在需要釋出事件的地方載入ApplicationContext,然後進行事件釋出

package com.container.event;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class DemoEventPublisher
{
@Autowired ApplicationContext applicationContext; public void publish(String message) { applicationContext.publishEvent(new DemoEvent(this, message)); } }

除了常見的Spring框架事件,比如ContextRefreshedEvent, SpringApplication 也會發送其他的application事件。
應用執行時,事件會以下面的次序傳送:

  1. 在執行開始,但除了監聽器註冊和初始化以外的任何處理之前,會發送一個 ApplicationStartedEvent 。
  2. 在Environment將被用於已知的上下文,但在上下文被建立前,會發送一個 ApplicationEnvironmentPreparedEvent 。
  3. 在refresh開始前,但在bean定義已被載入後,會發送一個 ApplicationPreparedEvent 。
  4. 在refresh之後,相關的回撥處理完,會發送一個 ApplicationReadyEvent ,表示應用準備好接收請求了。
  5. 啟動過程中如果出現異常,會發送一個 ApplicationFailedEvent

注 有些事件實際上是在 ApplicationContext 建立前觸發的,所以你不能在那些事件(處理類)中通過 @Bean 註冊監聽器,只能通過 SpringApplication.addListeners(…) 或 SpringApplicationBuilder.listeners(…) 方法註冊。如果想讓監聽器自動註冊,而不關心應用的建立方式,你可以在工程中新增一個 META-INF/spring.factories 檔案,並使用 org.springframework.context.ApplicationListener 作為key指向那些監聽器,如下:

org.springframework.context.ApplicationListener=com.example.project.MyListener