前端访问后台接口时需要验证token来获取权限,由于token的验证过程较为复杂,所以单独写了一个service类来处理token的逻辑。在把token代码独立出来之后,发现在每次访问都会报空指针异常,经过查看发现在拦截其中注入service的时候没有注入进去

 
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
 
 
    @Autowired
    private TokenService tokenService;
 
    public boolean preHandle (HttpServletRequest request,
                              HttpServletResponse response, Object handler) throws Exception {
        String requestUri = request.getRequestURI();
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod ();
        if (method.getAnnotation (Authorization.class) != null) {
            // 从 header 中得到 token
            String authorization = request.getHeader (SystemConstant.AUTHORIZATION);
            if(authorization == null){
//                response.setStatus (HttpServletResponse.SC_UNAUTHORIZED);
//                return false;
                String token = tokenService.createToken("2");
                authorization = token;
            }
            // 验证 token
            Claims claims = JWTUtils.parseJWT(authorization);
            if (claims != null && claims.size() > 0) {
                // 如果 token 验证成功,将 token 对应的用户 id 存在 request 中,便于之后注入
                JSONObject jsonObject=JSONObject.fromObject(claims.get("userinfo"));
                Map<String,Class> classMap = new HashMap<>();
                classMap.put("roles", UserInfo.Role.class);
                classMap.put("resources", UserInfo.Resource.class);
                UserInfo userInfo = (UserInfo) JSONObject.toBean(jsonObject, UserInfo.class,classMap);
                request.setAttribute (SystemConstant.CURRENT_USER_INFO, userInfo);
                return true;
            }else{
                // 如果验证 token 失败,并且方法注明了 Authorization,返回 401 错误
                response.setStatus (HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
        }else {
            return true;
        }
 
 
    }
}

查询资料网站之后发现了解决方法:

@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
 
    @Autowired
    AuthorizationInterceptor authorizationInterceptor;
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authorizationInterceptor);
    }
}

拦截器用注入的方式添加,而不是用new的方式。