Spring 5 Webflux中,替代拦截器实现控制器后置请求拦截的方案有哪些?
Spring Webflux中控制器执行后、业务逻辑前的拦截方案
在Spring Webflux中,替代Spring MVC方法拦截器(HandlerInterceptor)且能满足「请求进入控制器后、业务逻辑执行前」拦截需求的方案,主要有以下两种:
1. AspectJ环绕切面(@Around)
这是最通用、灵活的方案,通过切面精准定位控制器方法或特定业务方法,在方法执行前后插入自定义逻辑,完全适配响应式编程模型。
示例代码:
@Aspect @Component public class PostControllerEntryInterceptor { // 切入点:匹配所有控制器包下的方法 @Around("execution(* com.yourproject.controller..*(..))") public Object interceptControllerMethod(ProceedingJoinPoint joinPoint) throws Throwable { // 此处为「进入控制器后、业务逻辑执行前」的拦截逻辑 String methodName = joinPoint.getSignature().getName(); System.out.printf("开始执行控制器方法: %s,执行前预处理%n", methodName); // 执行原控制器方法(触发业务逻辑) Object result = joinPoint.proceed(); // 可选:业务逻辑执行后的后置处理(适配响应式类型) if (result instanceof Mono) { return ((Mono<?>) result) .doOnSuccess(res -> System.out.printf("控制器方法%s执行完成,后置处理%n", methodName)); } else if (result instanceof Flux) { return ((Flux<?>) result) .doOnComplete(() -> System.out.printf("控制器方法%s的Flux流完成,后置处理%n", methodName)); } return result; } }
注意事项:
- 确保项目引入了AspectJ依赖(Spring Boot中只需引入
spring-boot-starter-aop) - 处理返回值时必须适配
Mono/Flux类型,避免阻塞响应式流
2. RequestBodyAdvice(针对带请求体的接口)
如果你的拦截需求仅针对需要解析请求体的接口,可以实现RequestBodyAdvice接口,在请求体解析完成后、控制器方法执行前插入逻辑。
示例代码:
@ControllerAdvice public class CustomRequestBodyAdvice implements RequestBodyAdvice { @Override public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) { // 匹配需要拦截的控制器方法,返回true则生效 return true; } @Override public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException { return inputMessage; } @Override public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) { // 请求体解析完成后、控制器方法执行前的拦截逻辑 System.out.printf("控制器方法%s的请求体已解析,执行预处理%n", parameter.getMethod().getName()); return body; } @Override public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) { return body; } }
为什么不推荐过滤器?
Webflux的WebFilter是在请求到达控制器之前执行的,无法满足你「进入控制器后」的拦截需求,因此不适用。
内容的提问来源于stack exchange,提问作者KennyL123
相关产品推荐
相关产品推荐

