(题外话::前篇写了MVP篇)
一:Dagger2的逻辑图
注解:
@Inject:
通常在需要依赖的地方使用这个注解。换句话说,你用它告诉Dagger这个类或者字段需要依赖注入。这样,Dagger就会构造一个这个类的实例并满足他们的依赖。
@Module:
Modules类里面的方法专门提供依赖,所以我们定义一个类,用@Module注解,这样Dagger在构造类的实例
时候,就知道从哪里去找到需要的依赖。modules的一个重要特征是它们设计为分区并组合在一起(比如说,
我们的app中可以有多个组成在一起的modules)
@Provide:
在modules中,我们定义的方法是用这个注解,以此来告诉Dagger我们想要构造对象并提供这些依赖。
@Component:
Components从根本上来说就是一个注入器,也可以说是@Inject和@Module的桥梁,它的主要作用就是连接这两个部分。Components可以提供所有定义了的类型的实例,比如:我们必须用@Component注解一个接口然后列出所有的
gradle引入
dependencies { classpath 'com.android.tools.build:gradle:2.3.1' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' //添加apt命令 // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files }
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:25.3.1' compile 'com.android.support:design:25.3.1' compile 'com.android.support.constraint:constraint-layout:1.0.2' testCompile 'junit:junit:4.12' compile 'com.google.code.gson:gson:2.7' //butterknife compile 'com.jakewharton:butterknife:8.5.1' // annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1 apt 'com.jakewharton:butterknife-compiler:8.5.1' //dagger2 apt 'com.google.dagger:dagger-compiler:2.0.2' //指定注解处理器 compile 'com.google.dagger:dagger:2.0.2' //dagger公用api provided 'org.glassfish:javax.annotation:10.0-b28' //添加android缺失的部分javax注解 // okHttp compile 'com.squareup.okhttp3:okhttp:3.4.1' compile 'com.squareup.okhttp3:logging-interceptor:3.4.1' //retrofit compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0' compile 'com.squareup.retrofit2:converter-gson:2.1.0' }
二:Dagger2的代码实现
1.创建最高层AppModule
@Module public class AppModule { private Application mApplication; public AppModule(Application mApplication) { this.mApplication = mApplication; } @Provides @Singleton public Application provideApplication(){ return mApplication; } @Provides @Singleton public Gson provideGson(){ return new Gson(); } }2.创建最高层AppCompenent
@Singleton @Component(modules = {AppModule.class, HttpModule.class}) public interface AppCompenent { public ApiService getApiService(); }3.创建最高层Application
public class MyApplication extends Application{ private AppCompenent mAppCompenent; public static MyApplication get(Context context){ return (MyApplication)context.getApplicationContext(); } public AppCompenent getAppCompenent(){ return mAppCompenent; } @Override public void onCreate() { super.onCreate(); mAppCompenent = DaggerAppCompenent.builder().appModule(new AppModule(this)).httpModule(new HttpModule()).build(); } }4.创建最高层Singleton
@Scope @Documented @Retention(RUNTIME) public @interface ActivityScope { }5.创建Http网络层module
@Module public class HttpModule { @Provides @Singleton public OkHttpClient provideOkHttpClient(){ // log用拦截器 HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); // 开发模式记录整个body,否则只记录基本信息如返回200,http协议版本等 logging.setLevel(HttpLoggingInterceptor.Level.BODY); // 如果使用到HTTPS,我们需要创建SSLSocketFactory,并设置到client // SSLSocketFactory sslSocketFactory = null; return new OkHttpClient.Builder() // HeadInterceptor实现了Interceptor,用来往Request Header添加一些业务相关数据,如APP版本,token信息 // .addInterceptor(new HeadInterceptor()) .addInterceptor(logging) // 连接超时时间设置 .connectTimeout(10, TimeUnit.SECONDS) // 读取超时时间设置 .readTimeout(10, TimeUnit.SECONDS) .build(); } @Provides @Singleton public Retrofit provideRetrofit(OkHttpClient okHttpClient){ Retrofit.Builder builder = new Retrofit.Builder() .baseUrl(ApiService.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(okHttpClient); return builder.build(); } @Provides @Singleton public ApiService provideApiService(Retrofit retrofit){ return retrofit.create(ApiService.class); } }6.创建逻辑板块module
@Module public class RecommendModule { private RecommendContract.View mView; public RecommendModule(RecommendContract.View view) { this.mView = view; } @Provides public RecommendContract.Presenter providePresenter(RecommendContract.View view,RecommendModel model){ return new RecommendPresenter(view,model); } @Provides public RecommendContract.View provideView(){ return mView; } @Provides public RecommendModel provideModel(ApiService apiService){ return new RecommendModel(apiService); } }7.创建逻辑板块compenent
@ActivityScope @Component(modules = RecommendModule.class,dependencies = AppCompenent.class) public interface RecommendCompenent { void inject(WelcomeActivity activity); }8.Avtivity、Fragment的使用(使用之前先Rebuild Project自动生成DaggerRecommendCompenent类)
public class WelcomeActivity extends AppCompatActivity implements RecommendContract.View { @Inject//dagger2的注入 RecommendContract.Presenter mPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome);//dagger2的注入 DaggerRecommendCompenent.builder().appCompenent(((MyApplication)getApplication()).getAppCompenent()).recommendModule(new RecommendModule(this)).build().inject(this);mPresenter.requestDatas(); }
@Override
public void showLoading() { }
@Override
public void showError(String msg) {
Toast.makeText(this,"showError",Toast.LENGTH_SHORT).show();
}
@Override
public void dismissLoading() { }
@Override
public void showResult(List<AppInfo> datas) {
Toast.makeText(this,datas.get(0).getDisplayName(),Toast.LENGTH_SHORT).show();
}
@Override
public void showNodata() {
Toast.makeText(this,"showNodata",Toast.LENGTH_SHORT).show();
}
}