如何解决在实现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()
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。