springboot---监听ApplicationListener和ApplicationEvent简单使用

监听ApplicationListener和ApplicationEvent简单使用

本来想实现一个功能就是,在登录成功之后,将一些用户的信息,放入到session里面,本来想,在登录接口成功回调之后,在写,但是想做一个监听的动作,监听着登录成功的接口,之后走到监听函数里面,进行业务处理。

1、首先写一个监听类,之后实现ApplicationListener接口,实现其中的public void onApplicationEvent(ApplicationEvent event)方法,其实ApplicationListener接口可以使用泛型,但是我为了防止以后还有监听,所以我没有写泛型,而是在onApplicationEvent方法里面写了instanceof这个判断,主要是判断监听的event是不是你所要监听的事件。

package cn.springboot.yzpt.listener;

import cn.springboot.yzpt.common.SuccessfulAuthenticationEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

public class SuccessLoginListener implements ApplicationListener {

    private static Logger logger = LoggerFactory.getLogger(SuccessLoginListener.class);

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if(event instanceof SuccessfulAuthenticationEvent){

            SuccessfulAuthenticationEvent successfulAuthenticationEvent = (SuccessfulAuthenticationEvent)event;

            logger.info(successfulAuthenticationEvent.toString());
        }
    }

}

2、紧接着需要建立一个监听事件,需要继承ApplicationEvent这个类,这里面所需要的属性,自己去定义,我定义HttpServletRequest httpServletRequest; HttpServletResponse httpServletResponse; String sessionId,这三个属性,用来满足我的业务需求。

package cn.springboot.yzpt.common;

import org.springframework.context.ApplicationEvent;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class SuccessfulAuthenticationEvent extends ApplicationEvent {

    private static final long serialVersionUID = 3039313222160544111L;

    private HttpServletRequest httpServletRequest;
    private HttpServletResponse httpServletResponse;
    private String sessionId;

    public SuccessfulAuthenticationEvent(Object source,HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) {
        super(source);
        this.httpServletRequest = httpServletRequest;
        this.httpServletResponse = httpServletResponse;
    }


    public String getSessionId() {
        return sessionId;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    public HttpServletResponse getHttpServletResponse() {
        return httpServletResponse;
    }

    public void setHttpServletResponse(HttpServletResponse httpServletResponse) {
        this.httpServletResponse = httpServletResponse;
    }

    public HttpServletRequest getHttpServletRequest() {
        return httpServletRequest;
    }

    public void setHttpServletRequest(HttpServletRequest httpServletRequest) {
        this.httpServletRequest = httpServletRequest;
    }
}

3、接着需要在springboot的启动类里面配置一下监听。

package cn.springboot.yzpt;

import cn.springboot.yzpt.listener.SuccessLoginListener;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
@MapperScan("cn.springboot.yzpt.mapper")
public class YzptApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(YzptApplication.class, args);
        //装载监听
        context.addApplicationListener(new SuccessLoginListener());
    }
}

 4、这个时候需要设置一个触发这个事件的方法。

package cn.springboot.yzpt.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class EventPublisher {

    @Autowired
    private ApplicationContext applicationContext;

    public void pushlish(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
        applicationContext.publishEvent(new SuccessfulAuthenticationEvent(this,httpServletRequest,httpServletResponse));
    }
}

5、最后就是在自己的业务逻辑里面调用这个触发的方法了,在登录成功里面写这个触发的事件,用来处理这个接口之后的业务逻辑。

package cn.springboot.yzpt.controller.loginUser;

import cn.springboot.yzpt.common.CodeEnums;
import cn.springboot.yzpt.common.EventPublisher;
import cn.springboot.yzpt.common.HttpRequestEntity;
import cn.springboot.yzpt.exception.YzptException;
import cn.springboot.yzpt.server.loginUser.LoginUserServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/loginUser")
public class LoginUserController {

    private static Logger logger = LoggerFactory.getLogger(LoginUserController.class);

    @Autowired
    LoginUserServer loginUserServer;

    @Autowired
    EventPublisher eventPublisher;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public HttpRequestEntity login(@RequestBody Map<String, String> userInfo, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        HttpRequestEntity httpRequestEntity = new HttpRequestEntity();
        try {
            boolean loginType = loginUserServer.login(userInfo.get("user"), userInfo.get("password"));
            httpServletRequest.getSession().setAttribute("id", "12314434231");
            if (loginType) {
                httpRequestEntity.setMessage("登陆成功");


                eventPublisher.pushlish(httpServletRequest,httpServletResponse);

                logger.info(userInfo.get("user") + "登陆成功");
            }
        } catch (YzptException e) {
            httpRequestEntity.setCode(e.getCode());
            httpRequestEntity.setMessage(e.getErrMsg());
        } catch (Exception e) {
            logger.error("/loginUser/login:出现异常", e);
            httpRequestEntity.setCodeEnums(CodeEnums.SYSTEM_ERR);
        }
        return httpRequestEntity;
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值