Dagger 2 - two provides method that provide same interface

后端 未结 4 1269
慢半拍i
慢半拍i 2020-12-24 05:33

lets say I have:

public interface Shape  {}


public class Rectangle implements Shape {

}

public class Circle implements Shape {

}

and I

4条回答
  •  执笔经年
    2020-12-24 06:25

    I do not think it is a good idea to use the new operator within the constructor of the Module. This would create an instance of each of your provided objects upon initialization of your object graph (i.e. when you call new ApplicationModule()) instead of when Dagger needs the object for the first time. In this case (with only two objects), it would be negligible, but in larger projects this could cause a bottleneck upon the start of the application. Instead, I would follow the suggestion by @sector11, and instantiate your objects in the @Provides annotated methods.

    As for providing two objects of the same type, both @Jeff and @Amir are correct. You can either use the provided @Named() qualifier, or create your own qualifiers, like so:

    @Qualifier @Retention(RetentionPolicy.RUNTIME)
    public @interface RectangleShape {}
    
    @Qualifier @Retention(RetentionPolicy.RUNTIME)
    public @interface CircleShape {}
    

    Then your ApplicationModule should look like this:

    @Module
    public class ApplicationModule {
    
        @Provides @RectangleShape // @Named("rectangle")
        public Shape provideRectangle() {
            return new Rectangle();
        }
    
        @Provides @CircleShape // @Named("circle")
        public Shape provideCircle() {
            return new Circle();
        }
    
    }
    

    With this you can inject these objects into your classes like this:

    @Inject @RectangleShape /* @Named("rectangle") */ public Shape mRectangle;
    @Inject @CircleShape /* @Named("circle") */ public Shape mCircle;
    

    If you need to provide the instances of your Shape classes without an @Inject annotation, you can do so in your Component class:

    @Component(modules = { ApplicationModule.class })
    public interface ApplicationComponent {
    
        void inject(MyApplication application);
    
        @RectangleShape // @Named("rectangle")
        Shape getRectangle();
    
        @CircleShape // @Named("circle")
        Shape getCircle();
    
    }
    

    These methods will provide the same instance of each class provided by the @Provides annotated methods.

提交回复
热议问题