Dagger2浅析
Dagger2是由google與square公司聯合開發的一款依賴注入庫。
注解符號
@Inject 標注需要注入的對象
@Module 提供依賴注入的對象
@Provides 在Module中,負責提供注入對象的方法
@Component 負責將依賴注入對象提供給目標對象中,充當了橋梁的作用。
附加的注解
Scope 十分重要,標注了對象實例的范圍
Qualifier 限定符,為了防止依賴對象的注入產生混淆(因為可能需要對象名相同但內容不同)
Singleton
Dagger2創建步驟:
Step1
??????????使用@Inject標注需要的依賴注入對象
Step2
??????????使用@Module提供所需的依賴注入對象
Step3
??????????使用@Component做為橋梁,負責將依賴注入對象提供到目標對象中
Step4
??????????創建Component實例,完成對象的依賴注入
Gradle環境配置
project級build.gradle
buildscript {repositories {jcenter()}dependencies {classpath 'com.android.tools.build:gradle:2.1.2'classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'} }allprojects {repositories {jcenter()mavenCentral()maven {url 'https://oss.sonatype.org/content/repositories/snapshots'}} }task clean(type: Delete) {delete rootProject.buildDir }module級build.gradle
apply plugin: 'com.android.application' apply plugin: 'com.neenbedankt.android-apt'android {compileSdkVersion 23buildToolsVersion "23.0.3"defaultConfig {applicationId "com.android.dagger2demo"minSdkVersion 17targetSdkVersion 23versionCode 1versionName "1.0"}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'}}}dependencies {compile fileTree(dir: 'libs', include: ['*.jar'])testCompile 'junit:junit:4.12'compile 'com.android.support:appcompat-v7:23.4.0'compile 'com.google.dagger:dagger:2.4'apt 'com.google.dagger:dagger-compiler:2.4'//provided 'org.glassfish:javax.annotation:10.0-b28' }
創建步驟講解
Model實體
package com.android.dagger2demo;public class Student {private String id;private String name;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;} }
Step1 使用了@Inject注解所需依賴對象
Step2 使用@Module提供所需的依賴注入對象
Step3 使用@Component做為橋梁,負責將依賴注入對象提供到目標對象中
Step4 創建Component實例,完成對象的依賴注入
DaggerStudentComponent是有Dagger2編譯生成的,如果沒有,自己需要手動rebuild一下工程。
重要信息
若@Provides中的注解方法是static,則Component實例化可以使用create方式,即
StudentComponent component = DaggerStudentComponent.create( );
總結
- 上一篇: Dagger简单Demo
- 下一篇: 2016年Android实习岗位 腾讯二