简体   繁体   中英

how to get MicroProfile REST Client annotation in ClientRequestFilter

My RestClient is annotated by a custom annotation and I want to get the annotation value in a ClientRequestFilter.

Here is my MicroProfile RestClient:

@Path("/greetings")
@RegisterRestClient
@MyAnnotation("myValue") 
public interface MyRestClient{

  @GET
  public String hello();
}

I want to get the annotation value in my ClientRequestFilter:

public class MyFilter implements ClientRequestFilter {

  @Override
  public void filter(ClientRequestContext requestContext) {
   // Here i want to get the MyAnnotation value. i.e "myValue"
  }
}

I tried to call the requestContext.getClient().getAnnotations() method but it does not work since requestContext.getClient() is an instance of org.jboss.resteasy.microprofile.client.impl.MpClient

The implementation in question is RESTEasy. I would like to find a way to get this information from both RESTEasy classic and RESTEasy reactive implementations.

Thanks for your help

Here is the MicroProfile REST Client specific way :

@Provider
public class MyFilter implements ClientRequestFilter {
   
  public void filter(final ClientRequestContext clientRequestContext) {
    
    final Method method = (Method) clientRequestContext
                              .getProperty("org.eclipse.microprofile.rest.client.invokedMethod");
    
    Class<?> declaringClass = method.getDeclaringClass();
    System.out.println(declaringClass);

    MyAnnotation myAnnotation = declaringClass.getAnnotation(MyAnnotation.class);
    System.out.println(myAnnotation.value());
  }
}

which must work in all implementations including RESTEasy (Classic and Reactive) or Apache CXF.

This should work:

import org.jboss.resteasy.client.jaxrs.internal.ClientRequestContextImpl;

import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.ext.Provider;

@Provider
public class MyFilter implements ClientRequestFilter {
    @Override
    public void filter(ClientRequestContext requestContext) {
        Class<?> declaringClass = ((ClientRequestContextImpl) requestContext)
            .getInvocation()
            .getClientInvoker()
            .getDeclaring();

        MyAnnotation myAnnotation = declaringClass.getAnnotation(MyAnnotation.class);
        System.out.println(myAnnotation.value());
    }
}

Just to mention, this is really RESTEasy specific. The class ClientRequestContextImpl comes from the internal RESTEasy package and thus might be subject to change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM