w13221412326 2021-08-12 09:41 采纳率: 100%
浏览 396
已结题

自定义拦截器中 redisUtil工具类无法注入的问题

自定义拦截器

AuthenticationInterceptor

package com.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.annotation.LoginRequired;
import com.util.ContextHolder;
import com.util.RedisUtil;
import com.util.TokenUtil;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Objects;


public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    RedisUtil redisUtil;

    /**
     * 请求头
     */
    private static final String HEADER_AUTH = "Authorization";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        LoginRequired annotation = method.getAnnotation(LoginRequired.class);

        if(Objects.nonNull(annotation)) {
            String token = request.getHeader(HEADER_AUTH);

            // 如果没有填写,返回给前端无token信息
            if(Strings.isEmpty(token)) {
                returnJson(response);
                return false;
            }

            Map<String, Object> stringObjectMap = TokenUtil.resolveToken(token);
            String clientId = stringObjectMap.get("clientId").toString();
            // 首先从redis 从取出 token
            String redisToken = redisUtil.getKey(clientId);
            if(Strings.isEmpty(redisToken)) {
                returnJson(response);
                return false;
            }

            ContextHolder.setClientId(clientId);
            return true;

        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ContextHolder.shutdown();
    }

    private void returnJson(HttpServletResponse response){
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            Map<String, Object> result = returnJson(400, "用户令牌token无效");
            result.put("data", null);
            writer.print(result);
        } catch (IOException e){
            throw new RuntimeException("拦截器输出流异常");
        } finally {
            if(writer != null){
                writer.close();
            }
        }
    }


    private void returnNewToken(HttpServletResponse response, String newToken) {
        PrintWriter writer = null;

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try{
            writer = response.getWriter();
            Map<String, Object> result = returnJson(500, newToken);
            result.put("data", null);
            writer.print(result);
        }catch (IOException e) {

        }finally {
            if(writer != null) {
                writer.close();
            }
        }
    }

    public static JSONObject returnJson(Integer code, String msg) {
        JSONObject json = new JSONObject();
        json.put("code", code);
        json.put("msg", msg);
        return json;
    }

}


配置类

package com.conf;

import com.interceptor.AuthenticationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
public class AuthenticationConfiguration implements WebMvcConfigurer {


      @Bean
      public AuthenticationInterceptor authenticationInterceptor() {
          return new AuthenticationInterceptor();
      }


      @Override
      public void addInterceptors(InterceptorRegistry registry) {
          registry.addInterceptor(authenticationInterceptor()).addPathPatterns("/**");
      }
}


redisUtil 类

package com.util;

import com.domain.entity.BankUser;

import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
public class RedisUtil {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    public void putKeyObject(String key, BankUser bankUser, Long l, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, bankUser, l, timeUnit);
    }


    public void putKey(String key, String value, Long l, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, value, l, timeUnit);
    }

    public String getKey(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    public void removeKey(String key) {
        stringRedisTemplate.delete(key);
    }

}

感觉和redisUtl 类关系应该不大,应该我换成redisTemple 也是注入不进来的

  • 写回答

3条回答 默认 最新

  • w13221412326 2021-08-12 10:44
    关注

    这个问题已经解决了,主要是我写了两个conf类,另一个conf类中没有这段代码

     @Bean
          public AuthenticationInterceptor authenticationInterceptor() {
              return new AuthenticationInterceptor();
          }
    

    在添加监听器的时候

    public void addInterceptors(InterceptorRegistry registry) {
              registry.addInterceptor(authenticationInterceptor()).addPathPatterns("/**");
          }
    

    它加入的是没有被spring容器管理的监听器,而正确的conf类,并没有加进去,所以每次都是null

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 8月21日
  • 已采纳回答 8月13日
  • 创建了问题 8月12日

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站