我有一堆 Controller ,例如:
@RestController
public class AreaController {
@RequestMapping(value = "/area", method = RequestMethod.GET)
public @ResponseBody ResponseEntity<Area> get(@RequestParam(value = "id", required = true) Serializable id) { ... }
}
我需要拦截所有到达它们的请求,
我像这个例子创建了一个拦截器:
http://www.mkyong.com/spring-mvc/spring-mvc-handler-interceptors-example/
但它永远不会进入:(
因为我只使用注释,所以我没有 XML 来定义拦截器, 我发现它是这样设置的:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.test.app")
public class AppConfig extends WebMvcConfigurerAdapter {
@Bean
public ControllerInterceptor getControllerInterceptor() {
ControllerInterceptor c = new ControllerInterceptor();
return c;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getControllerInterceptor());
super.addInterceptors(registry);
}
}
我做错了什么或者我错过了什么?
最佳答案
您的 Interceptor
类 ControllerInterceptor
不是应用程序上下文管理的 bean。确保将 @Component
注释放在 ControllerInterceptor 上并将其包添加到 @ComponentScan
。因此,假设您的 ControllerInterceptor
位于包 com.xyz.interceptors 中,例如:
package com.xyz.interceptors; //this is your package
@Component //put this annotation here
public class ControllerInterceptor extends HandlerInterceptorAdapter{
// code here
}
并且您的 AppConfig 变为:
@ComponentScan(basePackages = { "com.test.app", "com.xyz.interceptors" })
public class AppConfig extends WebMvcConfigurerAdapter {
// ...
}
关于java - 如何拦截 spring REST Controller 中的所有请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35232597/