[Android] Adding Dagger2 to your project in 4 quick steps

1.- Gradle dependencies

[global build.gradle]

classpath ‘com.android.tools.build:gradle:2.1.0’
classpath ‘com.neenbedankt.gradle.plugins:android-apt:1.4’

repositories {
maven { url “https://jitpack.io” }


apply plugin: ‘com.android.application’
apply plugin: ‘com.neenbedankt.android-apt’

compile ‘com.google.dagger:dagger:2.0.2’
apt ‘com.google.dagger:dagger-compiler:2.0.2’
provided ‘javax.annotation:jsr250-api:1.0’

2.- Root Component

@Component(modules = MainModule.class)
public interface RootComponent {

void inject(BaseActivity activity);
void inject(App application);

// …. more injections here

3.- Main Module

public class MainModule {
App application;
LoggedUserFacade facade;

public MainModule(App application) {
this.application = application;
facade = new LoggedUserFacade(application);
// … More dependencies here

Context provideApplicationContext() {
return application.getApplicationContext();

// … rest of the @Provides-annotated methods

4.- Application class

public class App extends Application {
MainModule mainModule;
RootComponent component;

public void onCreate() {


private void initializeDependencyInjection() {
mainModule = new MainModule(this);
component = DaggerRootComponent.builder()

public RootComponent getComponent() {
return component;

@VisibleForTesting public void setComponent(RootComponent component) {
this.component = component;


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s