Search code examples
javaannotationsjax-rsguice

Is there a way to cause Guice to preserve annotations?


I'm trying to iterate over all classes that are annotated by an interface Bar, initialize them with Guice's Injector.createInstance, and register them with a Dropwizard Jersey server.

However, Guice's Injector.createInstance method seems to discard JAX-RS as well as custom annotations on every class. For some reason, the only thing that is preserved by Guice is the @MediaType annotation. The @Path annotation is lost, which prevents Jersey from properly handling HTTP requests.

Is there a way to force Guice to keep all existing annotations on these classes in its own generated implementation? Note that the injector was not configured to specifically handle instances of Foo, but the constructor of Foo is marked for injection.


Solution

  • Guice doesn't support this (yet)

    Guice has an open issue on this topic for more than 10 years and it's not resolved, and will probably never be.

    The only workaround is to use the @Inherited annotation on your annotations.

    But you mention you use existing annotations, not custom ones, so let's check them: @Consumes is @Inherited (great!), and so is @Produces (also great!), but @Path isn't (booh!), so indeed @Path isn't present on your Guice proxies.

    The only advice I could give you is to get rid of your Guice-AOP (TypeListener). If you can do that, then you very likely won't have any Guice proxies, and your methods will be on the top object, and therefore visible to Jersey.