欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

如何實現(xiàn)Spring?Event(異步事件)

 更新時間:2023年02月14日 10:50:21   作者:upupup-999  
這篇文章主要介紹了如何實現(xiàn)Spring?Event(異步事件)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

一、敘述

當Spring的事件(Application Event)為Bean和Bean之間的消息同步提供了支持。

當一個Bean處理完成一個任務之后,希望另外一個Bean知道并能做相應的處理,這時我們就需要讓另外一個Bean監(jiān)聽當前Bean所發(fā)生的事件

Spring的事件需要遵循如下流程

  • 自定義事件,繼承ApplicationEvent
  • 定義事件監(jiān)聽器,實現(xiàn)ApplicationListener
  • 使用容器發(fā)布事件

Spring框架中事件

Spring提供了以下5種標準的事件:

  • 上下文更新事件(ContextRefreshedEvent):在調用ConfigurableApplicationContext 接口中的refresh()方法時被觸發(fā)。
  • 上下文開始事件(ContextStartedEvent):當容器調用ConfigurableApplicationContext的Start()方法開始/重新開始容器時觸發(fā)該事件。
  • 上下文停止事件(ContextStoppedEvent):當容器調用ConfigurableApplicationContext的Stop()方法停止容器時觸發(fā)該事件。
  • 上下文關閉事件(ContextClosedEvent):當ApplicationContext被關閉時觸發(fā)該事件。容器被關閉時,其管理的所有單例Bean都被銷毀。

請求處理事件(RequestHandledEvent):在Web應用中,當一個http請求(request)結束觸發(fā)該事件。

如果一個bean實現(xiàn)了ApplicationListener接口,當一個ApplicationEvent被發(fā)布以后,bean會自動被通知

二、上Demo示例

1. pom文件

<!-- https://mvnrepository.com/artifact/org.springframework/org.springframework.context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>org.springframework.context</artifactId>
    <version>3.1.2.RELEASE</version>
</dependency>

2. 自定義一個事件繼承ApplicationEvent

import com.hrm.dto.ExamAnswer;
import org.springframework.context.ApplicationEvent;

/**
 * 考生答題事件
 */
public class AnswerEvent extends ApplicationEvent {
    private static final long serialVersionUID = 1L;
    public AnswerEvent(ExamAnswer answer) {
        super(answer);
    }
}

3. 自定義一個監(jiān)聽器實現(xiàn)ApplicationListener<自定義事件>

import com.hrm.dto.ExamAnswer;
import com.hrm.service.event.AnswerEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

/**
 * 答題監(jiān)聽事件
 */
@Component
@EnableAsync
public class AnswerEventListener implements ApplicationListener<ExamAnswer> {
    @Override
    public void onApplicationEvent(AnswerEvent answerEvent) {
        ExamAnswer answer = (ExamAnswer) answerEvent.getSource();
        if(answer != null) {
            super.save(answer);
        }
    }
}

4. 再來一個事件發(fā)布類

import com.hrm.dto.ExamAnswer;
import com.hrm.service.event.AnswerEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Repository;

@Repository
public class ExamAnswerDaoImpl implements ExamAnswerDao {
    @Autowired
    private ApplicationContext applicationContext;
    
	private void putAnswerToSpringEvent(ExamAnswer examAnswer) {
		發(fā)送Spring Event 事件
        applicationContext.publishEvent(new AnswerEvent(examAnswer));
    }
}

總結

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

最新評論