程序与技术分享:Android使用Dagger注入的方式初始化对象的简单使用

简介: 程序与技术分享:Android使用Dagger注入的方式初始化对象的简单使用

一. Dagger简介


Dagger 2 是 Google 开源的一款依靠注入结构,它的前身是 square 的 Dagger 1,Dagger 2 在 Android 中有着较为广泛的运用。


Dagger 2 根据 Java 注解,采用 annotationProcessor(注解处理器) 在项目编译时动态生成依靠注入需求的 Java 代码,然后咱们在合适的位置手动完结终究的依靠注入,而不是 Dagger 1 中根据反射的解决方案,所以在性能上是有保障的。


Android官方dagger介绍://代码效果参考:http://hnjlyzjd.com/xl/wz_24269.html


二. Dagger的依赖


// kapt is for implement annotation


apply plugin: 'kotlin-kapt'


// implementation dependences for dagger


implementation "com.google.dagger:dagger:2.21"


implementation "com.google.dagger:dagger-android-support:2.21"


kapt "com.google.dagger-compiler:2.21"


kapt "com.google.dagger-android-processor:2.21"


二. Dagger的配置


1. 初始化对象配置


1.1 使用@Inject注解初始化对象


注意:使用@Inject注解初始化对象时,构造函数所需的参数也必须已经使用dagger初始化,否则编译时会报错:com.record.sample.** cannot be provided without an @Inject constructor or an @Provides-annotated method


1 @Singleton


2 class RecordContractImple @Inject constructor(): RecordContract{


3   // empty body


4 }


1 @Singleton


2 class PicruteAdapter @Inject constructor(


3 context: Context


4 ): RecyclerView.Adapter{


5   // empty body


6 }


1.2 使用provide注解初始化对象


@Module


class RecordModule {


  @Provides


  @Singleton


  fun provideRecordAdapter(


    context: Context


  ): RecordAdapter = RecordAdapter(context)


  @Provides


  @Singleton


  fun provideRecordContract(


    recordContractImpl: RecordContractImpl  


  ): RecordContract = recordContractImpl


  @Provides


  @Singleton


  fun provideApplication(application: RecordApplication): RecordApplication = application


  @Provides


  @Singleton


  fun provideContext(application: RecordApplication): Context = application


}


使用@Named注解可以为同一个类初始化不同的对象,在页面中可以使用@Inject+@Named注解类使用该对象,但使用时一直报错: cannot be provided without an @Inject constructor or an @Provides-annotated method,原因未知。


// use @Named annotation to provide different instance for the same class


@Provides


@Singleton


@Named("Okhttp_client")


fun provideOkHttpClient(): OkHttpClient


@Provides


@Singleton


fun provideRetrofit(


  // use the @Named annotation to use different instance for same class


  @Named("Okhttp_client") okHttpClient: OkHttpClient


): Retrofit {


  return RetrofitProvide(...)


}


可以初始化基本类型


@Provider


fun provideAppVersion(): String = "2.21.0"


初始化Set,需要使用@ElementsIntoSet注解,网传dagger2.25以上版本有时候不需要显示提供@ElementsIntoSet注解。


@IntoSet注解告诉Dagger将返回的对象添加到Set依赖项中。


@Singleton


@Provides


@ElementsIntoSet


fun provideSet(): Set {


  val set = mutableSetOf()


  set.add("a")


  set.add("b")


  set.add("c")


  return set


}


@Singleton


@Provides


@ElementsIntoSet


fun provideSet2(): Set {


  val set = mutableSetOf()


  set.add("a")


  set.add("b")


  set.add("c")


  return set


}


@Provides


@IntoSet


fun provideInstanceForSet(): Name {


  return Name()


}


2. 绑定页面与使用Dagger初始化的对象


设置哪些页面可以使用@Inject方式获取Dagger初始化的对象。(ContributesAndroidInjector参数设置待确认)


@Module


interface BindRecordModule {


  @ContributesAndroidInjector


  fun bindMainActivity(): MainActivity


  @ContributesAndroidInjector


  fun bindHomeFragment(): HomeFragment


}


3. 定义Component配置moudle


将1和2中的配置配置到Component中,配置完点击make module后,Dagger会自动生成一个DaggerRecordComponent。


@Singleton


@Component(


  modules = 【


    // default module, must add


    AndroidSupportInjectionModule::class,  


    RecordModule::class,


    BindRecordModule::class,


  】


)


interface RecordComponent {


  @Component.Builder


  interface Builder {


    @BindsInstance


    fun application(application: Application): Builder


    fun build(): RecordComponent


  }


  fun inject(app: RecordApplication)


完成后点击Make Module,Dagger会自动生成类DaggerRecordComponent


4. 重写Application,配置Component


class RecordApplication: Application(), HasActivityInjector, HasSupportFragmentInjector {


  override fun onCreate() {


    DaggerRecordComponent.builder().


      .application(this)


      .build()


      .inject(this)


      super.onCreate()


  }


  @Inject


  internal lateinit var activityDispatchingAndroidInjector: DispatchingAndroidInjector


  override fun activityInjector(): AndroidInjector {


    return activityDispatchingAndroidInjector


  }


  @Inject


  internal lateinit var fragmentDispatchingAndroidInjector: DispatchingAndroidInjector


  override fun supportFragmentInjector(): AndroidInjector {


    return fragmentDispatchingAndroidInjector


  }


}


三. 使用


1. Activity中使用


AndroidInjection.inject(this)可以放在onAttach或者onCreate方法中初始化,只要在使用dagger初始化的地方之前调用即可。


HasSupportFragmentInjector可要可不要,原因未知。


class MainActivity: AppCompatActivity, HasSupportFragmentInjector {


  // use inject anotation to init instance, do not use private, otherwise the param will not init


  @Inject


  lateinit var recordContract: RecordContract


  override fun onCreate(savedInstanceState: Bundle?) {


    super.onCreate(savedInstanceState)


    // pass activity instance to dagger for init the param


    AndroidInjection.inject(this)


    // use the instance function directily


    val name = recordContract.getName()


  }


  @Inject


  internal lateinit var fragmentDispatchingAndroidInjector: DispatchingAndroidInjector


  override fun supportFragmentInjector(): AndroidInjector {


    return fragmentDispatchingAndroidInjector


  }


}


2. Fragment中使用


AndroidSupportInjection.inject(this)可以放在onAttach或者onCreate方法中初始化,只要在使用dagger初始化的地方之前调用即可。


class HomeFragment: Fragment() {


  // use inject anotation to init instance, do not use private, otherwise the param will not init


  @Inject


  lateinit var recordContract: RecordContract    


  override fun onAttach(context: Context) {


    super.onAttach(context)


    // pass activity instance to dagger for init the param


    AndroidSupportInjection.inject(this)


  }


}


不断更新中,技术讨论可以留言,谢谢。


end

目录
打赏
0
0
0
0
32
分享
相关文章
Android经典面试题之Kotlin延迟初始化的by lazy和lateinit有什么区别?
**Kotlin中的`by lazy`和`lateinit`都是延迟初始化技术。`by lazy`用于只读属性,线程安全,首次访问时初始化;`lateinit`用于可变属性,需手动初始化,非线程安全。`by lazy`支持线程安全模式选择,而`lateinit`适用于构造函数后初始化。选择依赖于属性特性和使用场景。**
232 5
Android经典面试题之Kotlin延迟初始化的by lazy和lateinit有什么区别?
Android studio 安装以及第一个程序
Android studio 安装以及第一个程序
218 0
Android端使用WebView注入一段js代码实现js调用android
Android端使用WebView注入一段js代码实现js调用android
210 0
程序与技术分享:Android应用安全之数据传输安全
程序与技术分享:Android应用安全之数据传输安全
kotlin安卓开发JetPack Compose 如何使用webview 打开网页时给webview注入cookie
在Jetpack Compose中使用WebView需借助AndroidView。要注入Cookie,首先在`build.gradle`添加WebView依赖,如`androidx.webkit:webkit:1.4.0`。接着创建自定义`ComposableWebView`,通过`CookieManager`设置接受第三方Cookie并注入Cookie字符串。最后在Compose界面使用这个自定义组件加载URL。注意Android 9及以上版本可能需要在网络安全配置中允许第三方Cookie。
1024 0
[Android]使用Dagger 2进行依赖注入 - Producers(翻译)
以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/6234811.html 使用Dagger 2进行依赖注入 - Producers 原文:http://frogermcs.github.io/dependency-injection-with-dagger-2-producers/ 本文是在Android中使用Dagger 2框架进行依赖注入的系列文章中的一部分。
1020 0
Termux安卓终端美化与开发实战:从下载到插件优化,小白也能玩转Linux
Termux是一款安卓平台上的开源终端模拟器,支持apt包管理、SSH连接及Python/Node.js/C++开发环境搭建,被誉为“手机上的Linux系统”。其特点包括零ROOT权限、跨平台开发和强大扩展性。本文详细介绍其安装准备、基础与高级环境配置、必备插件推荐、常见问题解决方法以及延伸学习资源,帮助用户充分利用Termux进行开发与学习。适用于Android 7+设备,原创内容转载请注明来源。
212 76
【01】仿站技术之python技术,看完学会再也不用去购买收费工具了-用python扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-客户的麻将软件需要下载落地页并且要做搜索引擎推广-本文用python语言快速开发爬取落地页下载-优雅草卓伊凡
【01】仿站技术之python技术,看完学会再也不用去购买收费工具了-用python扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-客户的麻将软件需要下载落地页并且要做搜索引擎推广-本文用python语言快速开发爬取落地页下载-优雅草卓伊凡
78 8
【01】仿站技术之python技术,看完学会再也不用去购买收费工具了-用python扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-客户的麻将软件需要下载落地页并且要做搜索引擎推广-本文用python语言快速开发爬取落地页下载-优雅草卓伊凡
【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
211 20
【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex

热门文章

最新文章