如何在Android项目中从头开始设置DAGGER依赖注入?

时间:2014-11-20 10:13:29

标签: android dependency-injection dagger dagger-2

如何使用Dagger?如何配置Dagger在我的Android项目中工作?

我想在我的Android项目中使用Dagger,但我发现它令人困惑。

编辑:Dagger2自2015年04月15日起也出局了,而且更令人困惑!

[这个问题是一个“存根”,我在我的答案中添加了更多关于Dagger1的知识,并且更多地了解了Dagger2。这个问题更像是一个指南而不是一个“问题”。]

3 个答案:

答案 0 :(得分:179)

指南 Dagger 2.x (修订版第6版)

步骤如下:

1。)Dagger添加到build.gradle个文件中:

  • 顶级 build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' //added apt for source code generation
    }
}

allprojects {
    repositories {
        jcenter()
    }
}
  • 应用级 build.gradle

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt' //needed for source code generation

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.2"

    defaultConfig {
        applicationId "your.app.id"
        minSdkVersion 14
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        debug {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    apt 'com.google.dagger:dagger-compiler:2.7' //needed for source code generation
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.google.dagger:dagger:2.7' //dagger itself
    provided 'org.glassfish:javax.annotation:10.0-b28' //needed to resolve compilation errors, thanks to tutplus.org for finding the dependency
}

2。)创建提供依赖关系的AppContextModule类。

@Module //a module could also include other modules
public class AppContextModule {
    private final CustomApplication application;

    public AppContextModule(CustomApplication application) {
        this.application = application;
    }

    @Provides
    public CustomApplication application() {
        return this.application;
    }

    @Provides 
    public Context applicationContext() {
        return this.application;
    }

    @Provides
    public LocationManager locationService(Context context) {
        return (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    }
}

3。)创建AppContextComponent类,该类提供接口以获取可注入的类。

public interface AppContextComponent {
    CustomApplication application(); //provision method
    Context applicationContext(); //provision method
    LocationManager locationManager(); //provision method
}

3.1。)这是您使用实现创建模块的方法:

@Module //this is to show that you can include modules to one another
public class AnotherModule {
    @Provides
    @Singleton
    public AnotherClass anotherClass() {
        return new AnotherClassImpl();
    }
}

@Module(includes=AnotherModule.class) //this is to show that you can include modules to one another
public class OtherModule {
    @Provides
    @Singleton
    public OtherClass otherClass(AnotherClass anotherClass) {
        return new OtherClassImpl(anotherClass);
    }
}

public interface AnotherComponent {
    AnotherClass anotherClass();
}

public interface OtherComponent extends AnotherComponent {
    OtherClass otherClass();
}

@Component(modules={OtherModule.class})
@Singleton
public interface ApplicationComponent extends OtherComponent {
    void inject(MainActivity mainActivity);
}

注意::您需要在模块@Scope上提供@Singleton注释(例如@ActivityScope@Provides)在您生成的组件中获取范围提供者的注释方法,否则它将是未编组的,并且每次注入时都会获得一个新实例。

3.2。)创建一个应用程序范围的组件,指定可以注入的内容(这与Dagger 1.x中的injects={MainActivity.class}相同):

@Singleton
@Component(module={AppContextModule.class}) //this is where you would add additional modules, and a dependency if you want to subscope
public interface ApplicationComponent extends AppContextComponent { //extend to have the provision methods
    void inject(MainActivity mainActivity);
}

3.3。)对于可以自己通过构造函数创建的依赖项,并且不想使用@Module重新定义(例如,您使用构建flavor来改变实现的类型),您可以使用@Inject带注释的构造函数。

public class Something {
    OtherThing otherThing;

    @Inject
    public Something(OtherThing otherThing) {
        this.otherThing = otherThing;
    }
}

此外,如果您使用@Inject构造函数,则可以使用字段注入而无需显式调用component.inject(this)

public class Something {
    @Inject
    OtherThing otherThing;

    @Inject
    public Something() {
    }
}

这些@Inject构造函数类会自动添加到同一作用域的组件中,而不必在模块中明确指定它们。

@Singleton范围内的组件中可以看到@Inject范围@Singleton构造函数类。

@Singleton // scoping
public class Something {
    OtherThing otherThing;

    @Inject
    public Something(OtherThing otherThing) {
        this.otherThing = otherThing;
    }
}

3.4。)在为给定界面定义特定实现后,如下所示:

public interface Something {
    void doSomething();
}

@Singleton
public class SomethingImpl {
    @Inject
    AnotherThing anotherThing;

    @Inject
    public SomethingImpl() {
    }
}

你需要"绑定"具有@Module

的接口的具体实现
@Module
public class SomethingModule {
    @Provides
    Something something(SomethingImpl something) {
        return something;
    }
}

Dagger 2.4之后的一个简写如下:

@Module
public abstract class SomethingModule {
    @Binds
    abstract Something something(SomethingImpl something);
}

4。)创建一个Injector类来处理您的应用程序级组件(它取代了整体ObjectGraph

(注意:Rebuild Project使用APT创建DaggerApplicationComponent构建器类)

public enum Injector {
    INSTANCE;

    ApplicationComponent applicationComponent;

    private Injector(){
    }

    static void initialize(CustomApplication customApplication) {
        ApplicationComponent applicationComponent = DaggerApplicationComponent.builder()
           .appContextModule(new AppContextModule(customApplication))
           .build();
        INSTANCE.applicationComponent = applicationComponent;
    }

    public static ApplicationComponent get() {
        return INSTANCE.applicationComponent;
    }
}

5。)创建您的CustomApplication课程

public class CustomApplication
        extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Injector.initialize(this);
    }
}

6。)CustomApplication添加到AndroidManifest.xml

<application
    android:name=".CustomApplication"
    ...

7。)MainActivity

中注入您的课程
public class MainActivity
        extends AppCompatActivity {
    @Inject
    CustomApplication customApplication;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Injector.get().inject(this);
        //customApplication is injected from component
    }
}

8。)享受!

+1。)您可以为组件指定Scope,您可以使用该组件创建活动级范围组件。 Subscopes允许您提供仅对给定子范围只需要的依赖关系,而不是整个应用程序。通常,每个Activity都使用此设置获得自己的模块。请注意,作用域提供程序存在每个组件,这意味着为了保留该活动的实例,组件本身必须在配置更改后继续存在。例如,它可以通过onRetainCustomNonConfigurationInstance()或Mortar范围存活。

有关subscoping的更多信息,请查看the guide by Google。另请参阅this site about provision methods以及component dependencies section)和here

要创建自定义范围,必须指定范围限定符注释:

@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface YourCustomScope {
}

要创建子范围,您需要在组件上指定范围,并指定ApplicationComponent作为其依赖关系。显然,您还需要在模块提供程序方法上指定子范围。

@YourCustomScope
@Component(dependencies = {ApplicationComponent.class}, modules = {CustomScopeModule.class})
public interface YourCustomScopedComponent
        extends ApplicationComponent {
    CustomScopeClass customScopeClass();

    void inject(YourScopedClass scopedClass);
}

@Module
public class CustomScopeModule {
    @Provides
    @YourCustomScope
    public CustomScopeClass customScopeClass() {
        return new CustomScopeClassImpl();
    }
}

请注意,只能将一个作用域组件指定为依赖项。可以想象它与Java中不支持多继承的方式完全相同。

+2。)关于@Subcomponent:基本上,范围@Subcomponent可以替换组件依赖关系;但是,您需要使用组件工厂方法,而不是使用注释处理器提供的构建器。

所以这个:

@Singleton
@Component
public interface ApplicationComponent {
}

@YourCustomScope
@Component(dependencies = {ApplicationComponent.class}, modules = {CustomScopeModule.class})
public interface YourCustomScopedComponent
        extends ApplicationComponent {
    CustomScopeClass customScopeClass();

    void inject(YourScopedClass scopedClass);
}

成为这个:

@Singleton
@Component
public interface ApplicationComponent {
    YourCustomScopedComponent newYourCustomScopedComponent(CustomScopeModule customScopeModule);
}

@Subcomponent(modules={CustomScopeModule.class})
@YourCustomScope
public interface YourCustomScopedComponent {
    CustomScopeClass customScopeClass();
}

而且:

DaggerYourCustomScopedComponent.builder()
      .applicationComponent(Injector.get())
      .customScopeModule(new CustomScopeModule())
      .build();

成为这个:

Injector.INSTANCE.newYourCustomScopedComponent(new CustomScopeModule());

+3。):请查看有关Dagger2的其他Stack Overflow问题,它们提供了大量信息。例如,我当前的Dagger2结构在this answer中指定。

<强>感谢

感谢您在GithubTutsPlusJoe SteeleFroger MCSGoogle上提供指南。

同样适用于此step by step migration guide I found after writing this post.

基尔的scope explanation

official documentation中的更多信息。

答案 1 :(得分:11)

指南 Dagger 1.x

步骤如下:

1。)将Dagger添加到build.gradle文件中以获取依赖项

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    ...
    compile 'com.squareup.dagger:dagger:1.2.2'
    provided 'com.squareup.dagger:dagger-compiler:1.2.2'

另外,添加packaging-option以防止有关duplicate APKs的错误。

android {
    ...
    packagingOptions {
        // Exclude file to avoid
        // Error: Duplicate files during packaging of APK
        exclude 'META-INF/services/javax.annotation.processing.Processor'
    }
}

2。)创建一个Injector类来处理ObjectGraph

public enum Injector
{
    INSTANCE;

    private ObjectGraph objectGraph = null;

    public void init(final Object rootModule)
    {

        if(objectGraph == null)
        {
            objectGraph = ObjectGraph.create(rootModule);
        }
        else
        {
            objectGraph = objectGraph.plus(rootModule);
        }

        // Inject statics
        objectGraph.injectStatics();

    }

    public void init(final Object rootModule, final Object target)
    {
        init(rootModule);
        inject(target);
    }

    public void inject(final Object target)
    {
        objectGraph.inject(target);
    }

    public <T> T resolve(Class<T> type)
    {
        return objectGraph.get(type);
    }
}

3。)创建RootModule以将未来的模块链接在一起。请注意,您必须包含injects来指定您将使用@Inject注释的每个类,否则Dagger会抛出RuntimeException

@Module(
    includes = {
        UtilsModule.class,
        NetworkingModule.class
    },
    injects = {
        MainActivity.class
    }
)
public class RootModule
{
}

4.如果您在Root中指定的模块中有其他子模块,请为这些子模块创建模块:

@Module(
    includes = {
        SerializerModule.class,
        CertUtilModule.class
    }
)
public class UtilsModule
{
}

5.)创建接收依赖关系的叶子模块作为构造函数参数。在我的情况下,没有循环依赖,所以我不知道Dagger是否可以解决这个问题,但我发现它不太可能。构造函数参数也必须在Module by Dagger中提供,如果指定complete = false,那么它也可以在其他模块中。

@Module(complete = false, library = true)
public class NetworkingModule
{
    @Provides
    public ClientAuthAuthenticator providesClientAuthAuthenticator()
    {
        return new ClientAuthAuthenticator();
    }

    @Provides
    public ClientCertWebRequestor providesClientCertWebRequestor(ClientAuthAuthenticator clientAuthAuthenticator)
    {
        return new ClientCertWebRequestor(clientAuthAuthenticator);
    }

    @Provides
    public ServerCommunicator providesServerCommunicator(ClientCertWebRequestor clientCertWebRequestor)
    {
        return new ServerCommunicator(clientCertWebRequestor);
    }
}

6。)扩展Application并初始化Injector

@Override
public void onCreate()
{
    super.onCreate();
    Injector.INSTANCE.init(new RootModule());
}

7.。在您的MainActivity中,使用onCreate()方法调用注射器。

@Override
protected void onCreate(Bundle savedInstanceState)
{
    Injector.INSTANCE.inject(this);
    super.onCreate(savedInstanceState);
    ...

8。)在@Inject中使用MainActivity

public class MainActivity extends ActionBarActivity
{  
    @Inject
    public ServerCommunicator serverCommunicator;

...

如果您收到错误no injectable constructor found,请确保您没有忘记@Provides注释。

答案 2 :(得分:0)

您可以在此处找到有用的Dagger2示例项目和教程。

Dagger 2 working sample project with MVP

Video tutorial

Practical tutorial