@Autowired在RequestInterceptor

时间:2018-06-06 10:34:53

标签: java spring spring-boot

@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课程的顶部添加了RequestEnvironment课程来自org.springframework.core.env.Environment

调试时,jwtUtils中的RequestInterceptornull

这可能是什么原因??

我尝试注入字段而不使用构造函数,但它仍然无效。

当我从@Service移除@ComponentJwtUtils时,我可以使用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());
     }
}

0 个答案:

没有答案