我有一个Spring Boot应用程序,我正在实现和拦截器以便记录一些数据。 问题是没有被呼叫,我已经尝试过:
@Interceptor
public class LoggerInterceptor{
@AroundInvoke
public Object collectBasicLoggingInformation(InvocationContext context) throws Exception {
Logger logger = LoggerFactory.getLogger(context.getClass());
logger.info("Method Called: " + context.getMethod()
.getName());
logger.info("Parameters: " + Arrays.toString(context.getParameters()));
return context.proceed();
}
}
然后我将其应用于方法或类,但在两者中均无效:
@GetMapping
@Interceptors(LoggerInterceptor.class)
public List getAllFilingNumber(){
logger.info("This is a test");
return filingNumberService.findAll();
}
或
@RestController
@RequestMapping(FilingNumberController.BASE_URL)
@Interceptors(LoggerInterceptor.class)
public class FilingNumberController{
@GetMapping
public List getAllFilingNumber(){
logger.info("This is a test");
return filingNumberService.findAll();
}
}
有人知道我在做什么错吗?
谢谢
答案 0 :(得分:2)
如果您具有springboot应用程序以拦截对控制器的请求,则必须采取不同的方法 altogethor。
拦截器与Java EE托管类结合使用 允许开发人员在关联目标上调用拦截器方法 类,以及方法调用或生命周期事件。 拦截器的常见用途是日志记录,审核和分析。 参考Doc
您正在尝试将Java EE注释与spring一起使用,这将无法正常工作。在spring-boot中,您将必须注册拦截器,例如:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleChangeInterceptor());
registry.addInterceptor(new ThemeChangeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");
registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/secure/*");
}
}
拦截器本身必须是扩展HandlerInterceptorAdapter
并实现以下方法的类。
从春季DOCS开始:
所有HandlerMapping实现都支持处理程序拦截器 当您想将特定功能应用于某些功能时非常有用 请求,例如检查主体。拦截器必须 从org.springframework.web.servlet实现HandlerInterceptor 包含三种方法的软件包,应提供足够的灵活性以 做各种预处理和后处理:
preHandle(..): Before the actual handler is executed postHandle(..): After the handler is executed afterCompletion(..): After the complete request has finished
@Component
public class RequestInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object object) throws Exception {
System.out.println("we are Intercepting the Request");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object object, ModelAndView model)
throws Exception {
System.out.println("request processing "
+ "completed by @RestController");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object object, Exception arg3)
throws Exception {
System.out.println("afterCompletion Request Completed");
}
}