SpringBoot中ApplicationEvent的使用步骤详解
介绍
ApplicationEvent类似于MQ,是Spring提供的一种发布订阅模式的事件处理方式。相对于MQ,其局限在于只能在同一个Spring容器中使用。
使用步骤
封装消息
将要发送的内容,封装成一个bean,这个bean需要继承ApplicationEvent类。
package com.example.event;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.context.ApplicationEvent;
/**
* @Description: 封装消息
* @author: zeal
* @date: 2024年04月09日 10:22
*/
@Setter
@Getter
@ToString
public class UserLoginEvent extends ApplicationEvent {
private Integer userId;
private String token;
public UserLoginEvent(Object source,Integer userId,String token) {
super(source);
this.userId=userId;
this.token=token;
}
}推送消息
推送消息时,注入ApplicationEventPublisher或ApplicationContext均可,调用publishEvent()方法。
package com.example.event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description: 消息推送
* @author: zeal
* @date: 2024年04月09日 10:26
*/
@RestController
@RequestMapping("event")
public class UserLoginController {
@Autowired
private ApplicationContext applicationContext;
@RequestMapping("/push")
public void pushEvent(){
UserLoginEvent userLoginEvent=new UserLoginEvent(this,001,"zsaf");
applicationContext.publishEvent(userLoginEvent);
}
}监听消息
此步骤相当于MQ的消费者,实现ApplicatonListener类,通过泛型来设置消息类型。
package com.example.event;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
/**
* @Description: 监听消息
* @author: zeal
* @date: 2024年04月09日 10:25
*/
@Component
public class UserLoginEventListener implements ApplicationListener<UserLoginEvent> {
@Override
public void onApplicationEvent(UserLoginEvent event) {
System.out.println("收到消息:"+event.toString());
}
}通过注解实现监听
package com.example.event;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
/**
* @Description: 监听消息
* @author: zeal
* @date: 2024年04月09日 10:25
*/
@Component
public class UserLoginEventListener{
@EventListener
public void onApplicationEvent(UserLoginEvent event) {
System.out.println("收到消息:"+event.toString());
}
}到此这篇关于SpringBoot中ApplicationEvent的用法的文章就介绍到这了,更多相关SpringBoot ApplicationEvent用法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Elasticsearch查询Range Query语法示例
这篇文章主要为大家介绍了Elasticsearch查询Range Query语法示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-04-04
springboot实现指定mybatis中mapper文件扫描路径
这篇文章主要介绍了springboot实现指定mybatis中mapper文件扫描路径方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-06-06
使用@Order控制配置类/AOP/方法/字段的加载顺序详解
这篇文章主要介绍了使用@Order控制配置类/AOP/方法/字段的加载顺序详解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-02-02


最新评论