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

自定义拦截器中 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日

悬赏问题

  • ¥15 如何用Thoony写ESP32温湿度检测无源蜂鸣器报警代码?
  • ¥20 部件内部的CT图像数据集
  • ¥15 Visual studio调用动态库
  • ¥15 双目摄像头标定后的校准文件
  • ¥15 powerbi举证增加度量值后出现对应关系错乱
  • ¥30 频率分析法分析绘制奈奎斯特图、波特图
  • ¥15 弹出来一万个系统找不到指定的文件框框,怎么解决
  • ¥15 ADS生成的微带线为什么是蓝色空心的
  • ¥15 求一下解题思路,完全不懂
  • ¥15 tensorflow