1. 程式人生 > >Spring的事件機制

Spring的事件機制

當把一個事件釋出到Spring提供的ApplicationContext中,被監聽器偵測到,就會執行對應的處理方法。

事件本身

事件是一個自定義的類,需要繼承Spring提供的ApplicationEvent

@Data
public class MyEvent extends ApplicationEvent {
    private String msg;

    public MyEvent(Object source, String msg) {
        super(source);
        this.msg = msg;
    }
}

事件監聽

基本方法是實現ApplicationListener介面,自定義一個監聽器,實現onApplicationEvent()方法,然後新增到ApplicationContext
比如:

public class MyListener implements ApplicationListener<MyEvent> {  

    @Override  
    public void onApplicationEvent(MyEvent event) {  
        System.out.print("監聽到MyEvent事件");  
    }  
}  
...
// SpringBoot的啟動類中新增監聽器
public static void main(String[] args) { SpringApplication application = new SpringApplication(MyApplication.class); application.addListeners(new MyListener()); application.run(args); }

也可以使用註解@EventListener(推薦):原理就是通過掃描這個註解,建立監聽器並新增到ApplicationContext

@Component
@Slf4j public class MyEventHandler { @EventListener public void handleEvent(MyEvent event) { log.info("------------處理事件:{}", event.getMsg()); try { Thread.sleep(5 * 1000L); log.info("事件1(5s)處理完成"); } catch (InterruptedException e) { e.printStackTrace(); } } }

事件釋出

可以通過上下文物件的釋出方法ConfigurableApplicationContext::publishEvent()來發布。
也可以實現ApplicationEventPublisherAware介面來發布(推薦)。

@Component
@Slf4j
public class EventService implements ApplicationEventPublisherAware {
    public ApplicationEventPublisher publisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }

    public String doEventWork(String msg) {
        log.info("------------publish event:" + msg);
        MyEvent event = new MyEvent(this, msg);
        publisher.publishEvent(event);
        return "OK";
    }
}

測試程式碼

@SpringBootTest
@RunWith(SpringRunner.class)
public class EventServiceTest {
    @Autowired
    private EventService service;

    @Test
    public void eventTest() {
        String msg="Java Code";
        service.doEventWork(msg);
    }
}

注意

如果2個事件之間是繼承關係,會先監聽到子類事件,處理完再監聽父類。

// MyEvent2 extends MyEvent

@Component
@Slf4j
public class MyEventHandler {

    @EventListener
    public void handleEvent(MyEvent event) {
        log.info("------------處理事件:{}", event.getMsg());
        try {
            Thread.sleep(5 * 1000L);
            log.info("事件1(5s)處理完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @EventListener
    public void handleEvent2(MyEvent2 event) {
        log.info("------------處理事件2:{}", event.getMsg());
        try {
            Thread.sleep(10 * 1000L);
            log.info("事件2(10s)處理完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

當我publish一個子類事件MyEvent2時,日誌如下:

預設是同步事件,如要使用非同步,需要開啟非同步,並使用@Async