@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 {
}
}
And then this is 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 }
}
I have added @Autowired on top of Request class. And Environment class is from org.springframework.core.env.Environment
When I debug, jwtUtils in RequestInterceptor is null.
What could be possible cause of this??
I tried injecting fields and not using constructor, but it still didn't work.
When I remove @Service and @Component from JwtUtils, I can use new operator to use JwtUtils in RequestInterceptor, but in that case the fields that are utowired inJwtUtils-RequestandEnvironment- becomenull`.
Case 2:
When I use JwtUtils in some other class with the @Service and @Component, there are no issues with it.
And this is how RequestInterceptor is registered
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestInterceptor());
}
}