Dagger 2 – Named

With the named attribute, you are able to create multiple instances of objects of the same class.  This is useful if you are configuring multiple objects that just have different configuration settings.

This is done using the @Named attribute which allows you to identify different instances that have the same class.

@Module
public class ServiceModule {
 
  @Provides
  @Singleton
  @Named("customerService")
  public ServiceGenerator provideCustomerServiceGenerator() {
    return new ServiceGenerator(Config.CUSTOMER_BASE_URL);
  }
 
  @Provides
  @Singleton
  @Named("paymentService")
  public ServiceGenerator providePaymentServiceGenerator() {
    return new ServiceGenerator(Config.PAYMENT_BASE_URL);
  }
}

Then to inject the named instance in to your application you include the named value as part of the @Inject annotation.

class MyActivity {
  @Inject @Named("customerService") ServiceGenerator customerService;
  @Inject @Named("paymentService") ServiceGenerator paymentService;
  ...
}

You can also inject them as part of an injected constructor.

class Transaction {

  @Inject
  public Transaction(@Named("paymentService") ServiceGenerator service) { 
    ...
  }
}

References:

Android Studio – Setting Member and Static Field Prefixes

While there is huge debate over the advantages and disadvantages of Hungarian notation and I generally disagree with much of it, I do still find it useful to differentiate member and static variables with the prefix m and s.

However, by default in Android Studio if you do that you and use code generation, such a generating getters and setters, it will include the prefix as part of the name for the generated code.  Thus a variable named mName which generate the getter  getmName() which gets annoying pretty quickly.

Fortunately there is an easy fix.  You can configure the prefixes for field and static fields in settings (File->Settings->Editor->Code Style->Java->Code Generation).  In this case the name prefixes can be set to “m” for member fields and “s” for static fields as shown below.

SettingsEditorCodeStyleJavaFields_mAnds

Now when you auto-generate the code you will get what you wanted.

public class User {
 
    String mName;
 
    public String getName() {
        return mName;
    }
 
    public void setName(String name) {
        mName = name;
    }
 
    public User(String name) {
        mName = name;
    }
}