Springboot事件实现

springboot事件实现,区别于使用消息队列的事件机制

生活中的事件,有触发事件的动作,事件发生了以后有处理事件的机制,事件的类型。带着这样的思路来理解springboot会如何事件。
首先定义事件,以面向对象的思路来理解,那应该是有接口或者是类来标识具备这样的方法的类就是事件类。
springboot使用ApplicationEvent做为事件类的父类。

import org.springframework.context.ApplicationEvent;
public class BusinessTrackEvent extends ApplicationEvent{
	/**
	 * Create a new ApplicationEvent.
	 *
	 * @param businessTrackEventEntity the object on which the event initially occurred (never {@code null})
	 */
	public BusinessTrackEvent(BusinessTrackEventEntity businessTrackEventEntity) {
		super(businessTrackEventEntity);
	}
}

接下来应该有一个处理事件的类,springboot中使用ApplicationListener接口来定义处理事件的监听类

@Log4j2
@Component
//Application<ApplicationEvent>泛型类型也可以使用BusinessTrackEvent,如果是一个监听方法监听不同类型的事件可以使用ApplicationEvent,如果针对具体某个事件的监听,泛型类型写具体的事件类型
public class CustomsEventListener implements ApplicationListener<ApplicationEvent>{

	@Autowired
	@Lazy
	private MongoTemplate mongoTemplate;
	@Autowired
	private BusinessTrackMapper businessTrackMapper;
	@Autowired
	private IAccountManagement accountManagement;

	@Async
	@Override
	@Transactional
	public void onApplicationEvent(ApplicationEvent event) {
		if(event instanceof CustomsEvent){
			CustomsEventEntity customsEventEntity=(CustomsEventEntity) event.getSource();
			mongoTemplate.insert(customsEventEntity);
		}
		if(event instanceof BusinessTrackEvent){
			BusinessTrackEventEntity businessTrackEventEntity=(BusinessTrackEventEntity) event.getSource();
			businessTrackEventEntity.setOperatorUsername(accountManagement.getUserName(businessTrackEventEntity.getOperatorUserId()));
			businessTrackMapper.saveBusinessTrack(businessTrackEventEntity);
		}

	}
}

发布事件,对外提供事件发布机制,使用ApplicationEventPublisher发布事件。

@Component
public final class PublisherCustomsEvent {

	@Autowired
	private ApplicationEventPublisher applicationEventPublisher;

	public void publisherEvent(ApplicationEvent applicationEvent){
		applicationEventPublisher.publishEvent(applicationEvent);
	}
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值