Quarkus中如何判断请求对应控制器方法是否含自定义注解?
在Quarkus中获取请求对应的控制器方法并判断自定义注解
在Quarkus里,你可以通过RESTEasy提供的API替代Spring中RequestMappingHandlerMapping的功能,以下是适配不同场景的实现方式:
方式一:使用RESTEasy响应拦截器(推荐)
如果你的需求是处理REST接口的请求/响应,优先采用RESTEasy的ContainerResponseFilter,它能直接获取当前请求匹配的控制器方法信息:
- 定义自定义注解(需确保为运行时保留):
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MyCustomAnnotation { }
- 编写响应拦截器,通过
@Context注入ResourceInfo获取目标方法:
@Provider public class ExampleResponseFilter implements ContainerResponseFilter { @Context private ResourceInfo resourceInfo; @Override public void filter(ContainerRequestContext requestCtx, ContainerResponseContext responseCtx) throws IOException { // 获取当前请求对应的控制器方法 Method targetMethod = resourceInfo.getResourceMethod(); // 检查方法是否带有自定义注解 if (targetMethod.isAnnotationPresent(MyCustomAnnotation.class)) { // 在这里执行你的响应处理逻辑 // 比如修改响应头、记录日志等 } } }
ResourceInfo是请求作用域对象,会自动绑定到当前请求匹配的REST资源方法,完全替代Spring中通过RequestMappingHandlerMapping查找处理方法的逻辑。
方式二:在Servlet Filter中获取目标方法
如果必须使用Servlet Filter(比如处理非REST的Servlet请求),可以通过RESTEasy的上下文工厂获取ResourceInfo:
@WebFilter(urlPatterns = "/*") public class ExampleFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { chain.doFilter(req, res); // 从RESTEasy上下文获取ResourceInfo ResourceInfo resourceInfo = ResteasyProviderFactory.getInstance().getContextData(ResourceInfo.class); if (resourceInfo != null) { Method targetMethod = resourceInfo.getResourceMethod(); if (targetMethod.isAnnotationPresent(MyCustomAnnotation.class)) { // 执行你的处理逻辑 } } } }
注意:这种方式仅对RESTEasy处理的REST接口请求有效,普通Servlet请求无法获取到ResourceInfo。
额外提示
- 自定义注解必须标注
@Retention(RetentionPolicy.RUNTIME),否则运行时无法通过反射检测到。 - 若使用Quarkus推荐的RESTEasy Reactive栈,上述代码完全兼容,无需修改。
内容的提问来源于stack exchange,提问作者BillUser88
相关产品推荐
相关产品推荐

