栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot事件实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot事件实现

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

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

import org.springframework.context.ApplicationEvent;
public class BusinessTrackEvent extends ApplicationEvent{
	
	public BusinessTrackEvent(BusinessTrackEventEntity businessTrackEventEntity) {
		super(businessTrackEventEntity);
	}
}

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

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

	@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);
	}
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1024848.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号