在实现Resource接口的类中处理自定义注释

问题描述

我正在尝试在实现实现定义资源的外部接口的类上处理自定义注释。设置如下:

资源接口,我无法对其进行修改:

@Path("/v1")
public interface Resource {

    @GET
    @Path("/foo")
    Response foo();

}

我可以修改的实现

public class ResourceImpl implements Resource {

    @Override
    @CustomAnnotation // has Retention.RUNTIME
    public Response foo() {
        // foo logic
    }
}

我已经实现了一个过滤器,以尝试处理覆盖的@CustomAnnotation方法上的foo()

@Provider
@ServerInterceptor
@Precedence("SECURITY")
public class CustomAnnotationInterceptor implements ContainerRequestFilter {

    @Context
    ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext containerRequestContext) throws IOException {
        // check if the invoked resource method is annotated with @CustomAnnotation and do logic
    }
}

但是,当我尝试从ResourceInfo实例获取匹配的资源类时,我得到了Resource接口,而当我获得匹配的方法时,我得到了foo()方法从缺少@CustomAnnotation的界面中访问。有什么办法解决吗?

我正在将RESTEasy用作JAX-RS的实现。

解决方法

您可以实现一个拦截器,在其中可以获取所调用的实际资源(方法和类)。拦截器应使用@InterceptorBinding绑定到您的注释(请参见54.2.4 Binding Interceptors to Components)。

// Interceptor
@Interceptor
@CustomAnnotation
@Priority(Interceptor.Priority.APPLICATION)
public class CustomAnnotationInterceptor {

    @AroundInvoke
    public Object interceptCustomAnnotation(InvocationContext ctx) throws Exception {
        CustomAnnotation customAnnotation = null;
        
        // The actual method being called
        Method method = ctx.getMethod();
        if (method != null) {
            customAnnotation = method.getAnnotation(CustomAnnotation.class);
        }

        // ... do stuff with the annotation

        return ctx.proceed();
    }
}

要获取实现您的接口的类的实例,可以使用ctx.getMethod().getDeclaringClass()ctx.getTarget().getClass().getSuperclass()

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...