@EventListener事件监听(监听某个实体)

@EventListener事件监听(监听某个实体)

码农世界 2024-05-19 后端 59 次浏览 0个评论

被监听对象是SysUserDto

package com.richfit.richfit.bootConfig.ListenerEvent;
import org.springframework.context.ApplicationEvent;
/**
 * 此类作为监听对象,监听登录用户  与方法queryZhuce在一块
 */
public class SysUserDto extends ApplicationEvent {
    private String userName;
    private String password;
    public SysUserDto(Object source, String userName, String password) {
        super(source);
        this.userName = userName;
        this.password = password;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

利用applicationContext.publishEvent 发布消息

@GetMapping("/queryZhuce")
    public List queryZhuce(@RequestParam(name = "username",required = false)String username,
                                      @RequestParam(name = "pass",required = false)String pass,
                                      HttpServletRequest request){
        //用于监听登录用户
        applicationContext.publishEvent(new SysUserDto(this,username,pass));
        return xqyService.queryZhuce(username,pass,request);
    }

用于接收发布的消息

package com.richfit.richfit.bootConfig.ListenerEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
/**
 * 接收被监听的对象
 */
@Configuration
public class CaiwuLIstenerEvent {
    @EventListener(SysUserDto.class)
    public void handle(SysUserDto sysUserDto){
        System.out.println("监听到的登录用户是:"+ sysUserDto.getUserName());
    }
}

以此可以实现对登录名的监听,从而实现某些需求

转载请注明来自码农世界,本文标题:《@EventListener事件监听(监听某个实体)》

百度分享代码,如果开启HTTPS请参考李洋个人博客
每一天,每一秒,你所做的决定都会改变你的人生!

发表评论

快捷回复:

评论列表 (暂无评论,59人围观)参与讨论

还没有评论,来说两句吧...

Top