Reputation: 10715
I am using Spring Boot(1.5.3) to develop a REST Web Service. In order to take some action on incoming request I have added an interceptor shown below.
@Component
public class RequestInterceptor extends HandlerInterceptorAdapter {
@Autowired
RequestParser requestParser;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
//HandlerMethod handlerMethod = (HandlerMethod) handler;
requestParser.parse(request);
return true;
}
}
RequestInterceptor
has an autowired Spring Bean RequestParser
responsible for parsing the request.
@Component
public class RequestParserDefault implements RequestParser {
@Override
public void parse(HttpServletRequest request) {
System.out.println("Parsing incomeing request");
}
}
Interceptor registration
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestInterceptor()).addPathPatterns("/usermanagement/v1/**");
}
}
And my Spring Boot Application
@SpringBootApplication
public class SpringBootApp {
public static void main(String[] args) {
SpringApplication.run(SpringBootApp.class, args);
}
}
Now when a request comes in, it lands in preHandle
method of RequestInterceptor
but RequestParser
is NULL. If I remove the @Component
annotation from RequestParser
I get an error during Spring context initialization No bean found of type RequestParser
. That means RequestParser
is registered as Spring bean in Spring context but why it is NULL at the time of injection? Any suggestions?
Upvotes: 2
Views: 3553
Reputation: 274
Your problem lies in this new RequestInterceptor()
.
Rewrite your WebMvcConfig to inject it, e.g. like this:
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Autowired
private RequestInterceptor requestInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(requestInterceptor)
.addPathPatterns("/usermanagement/v1/**");
}
}
Upvotes: 3