Android 依赖注入

Android 依赖注入java


Dagger2 ![https://github.com/google/dagger](github托管地址)android


1. 安装依赖:git

```github

    compile 'com.google.dagger:dagger:2.0.1'app

    compile 'com.google.dagger:dagger-compiler:2.0.1'ide

```gradle


2. 新建一个Component,这是一个接口:ui

```google

@Component(modules = ApplicationModule.class)spa

public interface ApplicationComponent {


}

```


3. 新建一个Module

```

@Module

public class ApplicationModule {

}

```


ok, 这里出错了,Error:(4, 24) 错误: 程序包javax.annotation不存在。

须要添加新的依赖,直接上最新的:

```

    compile 'org.glassfish:javax.annotation:10.0-b28'

```


能够查询一下![jcenter](https://bintray.com/bintray/jcenter/)


又不行了,DaggerApplicationComponent这个自动生成的类,怎么也导入不了。


解决方法:

在Project的build.gradle中加上:

```

buildscript {

    repositories {

        jcenter()

    }

    dependencies {

        classpath 'com.android.tools.build:gradle:1.2.3'

        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.7' //新增

    }

}

```


在app的build.gradle中添加:

```

apply plugin: 'com.android.application'

apply plugin: 'com.neenbedankt.android-apt'

```

修改dagger-compile的导入方式:

```

    apt 'com.google.dagger:dagger-compiler:2.0.1'

```


Sync.这样就能够找到那个自动生成的DaggerApplicationComponent,在Application的onCreate中生成Component:

```

component = DaggerApplicationComponent.builder()

                .applicationModule(new ApplicationModule())

                .build();

```


4. 添加注入

```

@Component(modules = ApplicationModule.class)

public interface ApplicationComponent {


    void inject(MercenaryApplication androidApplication);

    void inject(BaseActivity activity);

    void inject(BaseFragment fragment);


}

```


这几个都得在Application中提供注入。对应的Activity中也要注入。


5,ApplicationModule中提供Provider

```

    @Provides

    MercenaryApplication provideApplication() {

        return mApplication;

    }


    @Provides

    LayoutInflater provideLayoutInflater(){

        return LayoutInflater.from(mApplication);

    }

 ```


 这个基本结构已经出来了。


 代码上传到 ![MercenaryDemoAndroid](https://git.oschina.net/brightmoon/MercenaryDemoAndroid),能够查看 tag step-1.

相关文章
相关标签/搜索