问题描述
我正在尝试在实现实现定义资源的外部接口的类上处理自定义注释。设置如下:
资源接口,我无法对其进行修改:
@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()
。