实现Spring Event(异步事件)

实现Spring Event(异步事件)

一、叙述

当Spring的事件(Application Event)为Bean和Bean之间的消息同步提供了支持。当一个Bean处理完成一个任务之后,希望另外一个Bean知道并能做相应的处理,这时我们就需要让另外一个Bean监听当前Bean所发生的事件

Spring的事件需要遵循如下流程:
  1. 自定义事件,继承ApplicationEvent
  2. 定义事件监听器,实现ApplicationListener
  3. 使用容器发布事件
Spring框架中事件
Spring提供了以下5种标准的事件:

上下文更新事件(ContextRefreshedEvent):在调用ConfigurableApplicationContext 接口中的refresh()方法时被触发。
上下文开始事件(ContextStartedEvent):当容器调用ConfigurableApplicationContext的Start()方法开始/重新开始容器时触发该事件。
上下文停止事件(ContextStoppedEvent):当容器调用ConfigurableApplicationContext的Stop()方法停止容器时触发该事件。
上下文关闭事件(ContextClosedEvent):当ApplicationContext被关闭时触发该事件。容器被关闭时,其管理的所有单例Bean都被销毁。
请求处理事件(RequestHandledEvent):在Web应用中,当一个http请求(request)结束触发该事件。
如果一个bean实现了ApplicationListener接口,当一个ApplicationEvent被发布以后,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. 自定义一个监听器实现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;

/**
 * 答题监听事件
 */
@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. 再来一个事件发布类
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) {
		发送Spring Event 事件
        applicationContext.publishEvent(new AnswerEvent(examAnswer));
    }
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值