@Component
public class RequestInterceptor implements HandlerInterceptor {
private static Logger log = LoggerFactory.getLogger(RequestInterceptor.class);
@Autowired
JwtUtils jwtUtils;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("[RequestInterceptor] Request received is:" + request.toString());
String authHeader = request.getHeader("Authorization");
String token = authHeader.split(Constants.authorizationPrefix)[1];
log.info("token:" + token);
// JwtUtils jwtUtils = new JwtUtils();
DecodedJWT decodedJWT = jwtUtils.decode(token);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
然后这是JwtUtils:
@Service
@Component
public class JwtUtils {
private static Logger log = LoggerFactory.getLogger(JwtUtils.class);
private final Request request;
private final Environment environment;
@Autowired
public JwtUtils(Request request, Environment environment) {
this.request = request;
this.environment = environment;
}
public DecodedJwt decode(String token) { //decode here }
}
我在@Autowired
课程的顶部添加了Request
。 Environment
课程来自org.springframework.core.env.Environment
调试时,jwtUtils
中的RequestInterceptor
为null
。
这可能是什么原因??
我尝试注入字段而不使用构造函数,但它仍然无效。
当我从@Service
移除@Component
和JwtUtils
时,我可以使用new
运算符在JwtUtils
中使用RequestInterceptor
,但是case utowired in
字段{JwtUtils -
请求and
环境- become
null`。
案例2:
当我在JwtUtils
和@Service
的其他课程中使用@Component
时,就没有任何问题。
这就是RequestInterceptor的注册方式
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestInterceptor());
}
}