Skip to content
Advertisement

Migrating project from Guice to Dagger

I want to use Dagger in a project currently configured with Guice. I’m still very new to the concepts of DI, but I see that both Guice and Dagger use @Inject and @Provides notations. I have some understanding of the @Module and @Component annotations and how to set them up, but I’m wondering if the @Inject and and @Provides can basically be left as they are?

For example, let’s say I have this in Guice:

public class ModuleA extends AbstractModule {

   @Inject
   public ModuleA() {
     ...
   }

   @Provides
   @Singleton
   protected InterfaceX() {
    ...
   }

}

Could the following dagger implementation work the same, assuming there is also a component etc?

@Module
public class ModuleA {

   @Inject
   public ModuleA() {
     ...
   }

   @Provides
   @Singleton
   protected InterfaceX() {
    ...
   }

}

One thing that confused me was that @Provides is used in Dagger to bind implementations to interfaces, and I’m not sure if that’s what it is used for in Guice. Again, I’m pretty new to this so any clarification would be really appreciated. Thanks!

Advertisement

Answer

NOTE: Have not used Dagger but can clarify on Guice side.

@Provides in Guice is for informing the Guice injector about which method to use to for creating the asked object at build time. for eg : class Parent has implementation in 2 sub classes Child1 and Child2 Now you want to have a logic which defines when to inject Child1 and when to inject child2. This logic can be written in a method which can become the provider for Parent class impl. and to declare this provider method, @Provides annotation is used

class Parent {}
class Child1 extends Parent {}
class child2 extends Parent {}

GuieModule {
    @Provides
    Parent getParent() {
    if(something)
        return new Child1();
    else 
        return new child2();
    }
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement