Skip to content
This repository has been archived by the owner on Feb 26, 2023. It is now read-only.

Dagger2Integration

Tamas Vegh edited this page Sep 7, 2017 · 2 revisions

Integrating AndroidAnnotation with Dagger2

Dagger 2 and AndroidAnnotations can easily work together, combined usage of both frameworks is described here. This guide uses Dagger 2; for Dagger 1, see this guide. The article assumes that the reader is familiar with Dagger 2 usage of normal Android projects. If not, the Dagger documentation and example projects should be read first.

Injecting into AndroidAnnotations components with Dagger 2

Injecting dependencies into AA annotated components does not require any additional step than normal Dagger 2 usage. You have to annotate the components with AA annotations as usual, and you have to declare the annotated class (not the generated class) in your @Components.

@EActivity
public class DaggerActivity extends Activity {

  @AfterInject
  void onInjectDependencies() {
    ((MyApplication) getApplication()).component().inject(this);
    // dependency is now available
  }

  @Inject
  DaggerDependency dependency;
}
public class DemoApplication extends Application {
  
  @Singleton
  @Component(modules = AndroidModule.class)
  public interface ApplicationComponent {
    void inject(DaggerActivity daggerActivity);
  }
  
  private ApplicationComponent component;

  @Override public void onCreate() {
    super.onCreate();
    component = DaggerMyApplication_ApplicationComponent.builder()
        .androidModule(new AndroidModule(this))
        .build();
  }

  public ApplicationComponent component() {
    return component;
  }
}

Providing @EBean

If you want to use Dagger to inject an instance of an AA enhanced class, like @EBean, you have to add a @Provides method in your module. In that method, you have to create an instance of the generated class, by calling the generated methods manually.

@EBean
public class SomeDependency {
    // ...
}
@Module
public class DaggerModule {

    @Provides
    SomeDependency provideSomeDependency(Context context) {
        return SomeDependency_.getInstance_(context);
    }
}

You have to also provide an Android Context object, as usual in Dagger Android projects. After this is done, you can inject the @EBean with Dagger to another class:

public class DaggerClass {
    
    @Inject
    SomeDependency someDependency; // will have an instance of SomeDependency_
}

Using AndroidAnnotations

Questions?

Enjoying AndroidAnnotations

Improving AndroidAnnotations

Extending AndroidAnnotations

Clone this wiki locally