Dagger 2 - two provides method that provide same interface

后端 未结 4 1273
慢半拍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:03

    @Qualifier annotations are the right way to distinguish different instances or injection requests that have the same type. The main User's Guide page has a whole section on them.

    @Qualifier @Retention(RUNTIME)
    public interface Parallelogram {} /* name is up to you */
    
    // In your Module:
    @Provides @Parallelogram
    public Shape provideRectangle() {
        return rec ;
    }
    
    // In your other injected types:
    @Inject @Parallelogram Shape parallelogramShape;
    // or
    @Inject @Parallelogram Provider parallelogramShapeProvider;
    
    // In your Component:
    @Parallelogram Shape provideRectangle();
    

    Aside: Though I agree with sector11 that you shouldn't use new in injected types, Modules are exactly the correct place to call new if needed. Aside from adding the qualifier annotations, I'd say your Module looks just right to me.


    EDIT regarding the use of @Named compared to custom qualifier annotations:

    • @Named is a built-in @Qualifier annotation, much like the one I've created above. For simple cases, it works great, but because the binding is just a string you won't get as much help from your IDE in detecting valid keys or autocompleting the key.
    • Like with Named's string parameter, custom qualifiers can have string, primitive, enum, or class literal properties. For enums, IDEs can often autocomplete valid values.
    • @Named and custom qualifiers can be accessed from annotations in exactly the same way by specifying the annotation on the component method, as I've done with @Parallelogram above.

提交回复
热议问题