Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Jersey work with Dagger dependency injection?

Jersey normally uses HK2 dependency injection, but I would like to use Jersey with Dagger 2. Both Dagger and HK2 implement JSR 330, which I have taken as evidence that this should be possible without too much effort. I found ways to make Jersey work with CDI (e.g. Weld), Spring DI and Guice, but I can't find anything on Dagger.

To provide some context: I'm running a Grizzly–Jersey server in an SE environment, not in an EE container. My Maven project has com.google.dagger:dagger and org.glassfish.jersey.containers:jersey-container-grizzly2-http as dependencies, but not org.glassfish.jersey.inject:jersey-hk2, since I want to replace HK2 with Dagger.

The resource classes look like this:

@Path("/example") public final class ExampleResource {      private final Dependency dependency;      @Inject     public ExampleResource(final Dependency dependency) {         this.dependency = Objects.requireNonNull(dependency);     }      @GET     @Produces(MediaType.APPLICATION_JSON)     public Example getExample() {         return this.dependency.giveExample();     }  } 

And the Dagger component could e.g. be defined as follows:

@Component public interface Application {      public ExampleResource exampleEndpoint();     public XyzResource xyzEndpoint();     // etc.  } 

So that the main method would look similar to:

public final class Main {      public static void main(final String[] args) {         final Application application = DaggerApplication.create();         final URI baseUri = UriBuilder.fromUri("http://0.0.0.0/").port(80).build();         final ResourceConfig resourceConfig = new ResourceConfig();         // how to initialize `resourceConfig` using `application`?         final HttpServer httpServer = GrizzlyHttpServerFactory                 .createHttpServer(baseUri, resourceConfig, false);         try {             httpServer.start();         } catch (final IOException ex) {             ...         }     }  } 

Running the application immediately results in an exception: IllegalStateException: InjectionManagerFactory not found. It seems that a Dagger implementation of this factory is needed.

My question is: how to integrate Dagger with Jersey?

like image 653
Rinke Avatar asked Mar 11 '18 14:03

Rinke


People also ask

What does @inject do dagger?

The @Inject annotation println("Heater is hot !!!") Each class has an empty constructor with the @Inject annotation. This allows instances of these classes to be constructed by Dagger. The @Singleton annotation means that Dagger will create and maintain a single instance of the annotated class.

What is the benefit of dagger?

Benefits of using Dagger Dagger frees you from writing tedious and error-prone boilerplate code by: Generating the AppContainer code (application graph) that you manually implemented in the manual DI section. Creating factories for the classes available in the application graph.

What is dagger2?

Dagger 2 is a compile-time android dependency injection framework that uses Java Specification Request 330 and Annotations. Some of the basic annotations that are used in dagger 2 are: @Module This annotation is used over the class which is used to construct objects and provide the dependencies.

How does a dagger work?

To understand it better during a basic course, think module as a provider of dependency and consider an activity or the other class as a consumer. Now to supply dependency from provider to consumer we have a bridge between them, in Dagger, Component work as that specific bridge.


Video Answer


1 Answers

You shouldn't think of it as "how to integrate dagger with jersey". Figure out how to setup jersey, then once you have that figured out, then you can worry about using dagger.

Here's (very roughly) how I would do it.

Create your own implementation of the ResourceConfig class.

@ApplicationPath("/service") public class MyResourceConfig extends ResourceConfig {      @Inject     public MyResourceConfig(             @Nonnull final ExampleResource exampleResource) {         this.register(exampleResource);     }  } 

Then create a module that sets up everything you need to create an HttpServer

@Module public class MyServiceModule {      @Provides     @Singleton     @Named("applicationPort")     public Integer applicationPort() {         return 80;     }      @Provides     @Singleton     @Named("applicationBaseUri")     public URI baseUri(             @Named("applicationPort") @Nonnull final Integer applicationPort) {         return UriBuilder.fromUri("http://0.0.0.0/").port(applicationPort).build();     };      @Provides     @Singleton     public HttpServer httpServer(             @Named("applicationBaseUri") @Nonnull final URI applicationBaseUri,             @Nonnull final MyResourceConfig myResourceConfig) {         return GrizzlyHttpServerFactory                 .createHttpServer(applicationBaseUri, myResourceConfig, false);     }  } 

Then create your component that exposes the HttpServer. I typically like to make components that expose as little as possible. In this case, all you need to expose is the HttpServer.

@Singleton @Component(modules = { MyServiceModule.class }) protected interface ServiceComponent {      HttpServer httpServer();      @Component.Builder     interface Builder {          // Bind any parameters here...          ServiceComponent build();      }  } 

Then just go ahead and build your component, and start your HttpServer

public static void main(String[] args) {     final ServiceComponent component = DaggerServiceComponent.builder().build()     try {         component.httpServer().start();     } catch (Exception ex) {         // handle exception...     } } 

One more thing to note. I personally do not ever use the @Named("") annotation. I prefer to use a Qualifier. So you create a Qualifier annotation with a unique value. Then you can inject things like

@Provides @Singleton @MyUniqueQualifier public String myUniqueQualifierProviderValue() {     return "something"; } 

Then when injecting it

@Inject public SomeClass(@MyUniqueQualifier @Nonnull final String myUniqueQualifiedValue)  

If you use the @Named annotation you don't get compile time checks for conflicts or missing values. You would find out at run time that a value was not injected or then name conflicts with something else. It gets messy quick.

like image 156
Callan Avatar answered Sep 29 '22 03:09

Callan