user3329544
user3329544

Reputation: 69

Use of @Binds with @Named in Dagger 2

I have my module as shown below,

@Module
public abstract class BindsModuleEx {

    @Binds
    @Named("obj2")
    public abstract SomeInterface provideSomeInterface2(SomeInterfaceImpl2 someInterfaceImpl);

    @Binds
    @Named("obj1")
    public abstract SomeInterface provideSomeInterface1(SomeInterfaceImpl1 someInterfaceImpl);
}

My implementations of SomeInterface as shown below

public class SomeInterfaceImpl1 implements SomeInterface {
  @Inject
  @Named("obj1")
  public SomeInterfaceImpl1() {
  }

public class SomeInterfaceImpl2 implements SomeInterface {

  @Inject
  @Named("obj2")
  public SomeInterfaceImpl2() {
  }

Can I use @Named or @Qualifier on @Binds methods ? I am aware of using @Provides with @Named but I would like to know why this doesn't work and whats the right way to solve this kind of situation.

The error message reads like this

error: @Qualifier annotations are not allowed on @Inject constructors.

~Thanks in Advance.

Upvotes: 2

Views: 2716

Answers (2)

user3329544
user3329544

Reputation: 69

This is how I modified it, and it works.

public class MainActivity extends BaseActivity {

    @Inject
    @Named("obj1")
    SomeInterface someInterface1;

    @Inject
    @Named("obj2")
    SomeInterface someInterface2;
}

This is how my Implementations of SomeInterface is now

public class SomeInterfaceImpl1 implements SomeInterface {
  @Inject
  public SomeInterfaceImpl1() {
  }

Upvotes: -1

Chris
Chris

Reputation: 2362

The @Named qualifier doesn't go on the constructor declaration - you need to use it on your injection target, e.g. if you were injecting "obj1" in an Activity that's where you would use the qualifier.

Upvotes: 2

Related Questions