我使用Spring Boot(1.5.3)开发REST Web服务。为了对传入请求采取某些操作,我添加了一个拦截器,如下所示。
@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
有一个自动装配的Spring Bean RequestParser
负责解析请求。
@Component
public class RequestParserDefault implements RequestParser {
@Override
public void parse(HttpServletRequest request) {
System.out.println("Parsing incomeing request");
}
}
拦截器注册
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestInterceptor()).addPathPatterns("/usermanagement/v1/**");
}
}
我的Spring Boot应用程序
@SpringBootApplication
public class SpringBootApp {
public static void main(String[] args) {
SpringApplication.run(SpringBootApp.class, args);
}
}
现在,当请求进入时,它会以preHandle
RequestInterceptor
方法登陆,但RequestParser
为NULL。如果我从@Component
中删除RequestParser
注释,则在Spring上下文初始化No bean found of type RequestParser
期间出现错误。这意味着RequestParser
在Spring上下文中注册为Spring bean,但为什么它在注入时为NULL?有什么建议?
答案 0 :(得分:1)
你的问题在于new RequestInterceptor()
。
重写你的WebMvcConfig以注入它,例如像这样:
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Autowired
private RequestInterceptor requestInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(requestInterceptor)
.addPathPatterns("/usermanagement/v1/**");
}
}