国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > 綜合 > 正文

kotlin使用Dagger2的過程全紀(jì)錄

2024-07-21 23:03:43
字體:
供稿:網(wǎng)友

前言

Dagger2作為依賴注入神器,相信很多朋友都聽說過它的大名。只不過它的有些概念,理解起來并不是那么清晰,并且在使用的過程中,也比較迷糊。

Dagger2有Google接手開發(fā)的一個基于JSR-330標(biāo)準(zhǔn)的依賴注入框架,它會在編譯期間自動生成相關(guān)代碼,負(fù)責(zé)依賴對象的創(chuàng)建,達(dá)到解耦目的。

下面將詳細(xì)介紹關(guān)于kotlin/281154.html">kotlin使用Dagger2的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面話不多說了,來一起看看詳細(xì)的介紹吧。

kotlin中配置Dagger2

在app模塊的build.gradle文件中進(jìn)行如下配置,關(guān)于kapt的相關(guān)知識。

apply plugin: 'com.android.application'apply plugin: 'kotlin-android'apply plugin: 'kotlin-android-extensions'apply plugin: 'kotlin-kapt'android { ...}dependencies { ... implementation 'com.google.dagger:dagger:2.11' kapt 'com.google.dagger:dagger-compiler:2.11'}

相關(guān)常用注解:

  • @Inject
  • @Component
  • @Module
  • @Provides
  • @Qualifier和@Named
  • @Scope和@Singleton

@Inject

@Inject注解只是JSR-330中定義的注解,在javax.inject包中。 這個注解本身并沒有作用,它需要依賴于注入框架才具有意義,可以用來標(biāo)記構(gòu)造函數(shù)、屬性和方法。

標(biāo)記構(gòu)造函數(shù)

被標(biāo)記的構(gòu)造函數(shù)可以有0個或多個依賴作為參數(shù)。

同一個類中最多只可以標(biāo)記一個構(gòu)造函數(shù)。

class People @Inject constructor(val name:String = "Tom")

注意在kotlin中這種寫法是不被允許的,因為這等價于java中的多個構(gòu)造方法People(String name), People() 正確的寫法應(yīng)該是這樣:

data class People constructor(val name: String) { @Inject constructor() : this("Tom")}

標(biāo)記屬性

被標(biāo)記的屬性不能是final的,kotlin中不能是val。

被注入進(jìn)的屬性不能用private修飾(是Dagger2不支持,而非@Inject不支持)。

 @Inject lateinit var people:People

標(biāo)記方法

被標(biāo)記的方法可以有0個或多個依賴作為參數(shù)。

方法不能是抽象的。

class HomeActivity : AppCompatActivity() { private lateinit var people:People @Inject fun setPeople(people:People){ this.people = people }}

這種方法注入和屬性注入并沒有什么本質(zhì)上的不同,實現(xiàn)效果也基本一樣。還有一種做法是@Inject標(biāo)記被注入類的某個方法,該方法會在類的構(gòu)造方法之后接著被調(diào)用:

data class People constructor(val name: String) { @Inject constructor() : this("Tom") init { println("init:$name") } @Inject fun hello(){ println("hello:$name") }}class HomeActivity : AppCompatActivity() { @Inject lateinit var people:People override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) //執(zhí)行相關(guān)注入操作 ... println(people.toString()) }}

運行結(jié)果是這樣的:

01-02 11:57:30.995 16601-16601/? I/System.out: init:Tom01-02 11:57:30.995 16601-16601/? I/System.out: hello:Tom01-02 11:57:30.995 16601-16601/? I/System.out: People(name=Tom)

@Component

可以理解為一個注射器,可以算是Dagger2中最核心的一個注解,用來標(biāo)記一個接口或者抽象類。使用@Component標(biāo)記的接口,會在編譯時自動生成一個Dagger+類名的實現(xiàn)類實現(xiàn)依賴注入。在Component中一般可以定義兩種方法:

Members-injection methods:

該方法有一個參數(shù),表示需要注入到的類,提醒Dagger在該類中尋找需要被注入的屬性(被@Inject標(biāo)記)。

void inject(SomeType someType);//無返回值SomeType injectAndReturn(SomeType someType);//返回它的參數(shù)類型

等價于:

MembersInjector<SomeType> getMembersInjector();//使用MembersInjector.injectMembers方法注入

Provision methods:

該方法沒有參數(shù),返回一個需要被注入(或被提供)的依賴。一般用于為其他Component提供依賴的時候。

SomeType getSomeType();Provider<SomeType> getSomeTypeProvider();//可以通過Provider.get訪問任意次Lazy<SomeType> getLazySomeType();//通過Lazy.get第一次訪問時創(chuàng)建實例,并在之后的訪問中都訪問同一個實例
@Componentinterface HomeComponent { fun inject(activity: HomeActivity) fun injectAndReturn(activity: HomeActivity): HomeActivity fun getInjectors(): MembersInjector<HomeActivity>  fun getPeople():People}

事實上,了解到這里我們已經(jīng)可以使用最簡單的Dagger2用法,畢竟有了依賴和注射器,只需要注入就可以了,我們來看一個最簡單的Dagger2實例,只使用@Inject和@Component來完成注入。

第一步:在需要被注入的類的構(gòu)造方法上添加注解@Inject

class People @Inject constructor() { fun hello(){  println("hello") }}

第二步:編寫一個注射器接口

@Componentinterface HomeComponent { fun inject(activity: HomeActivity)}

第三步:注入

class HomeActivity : AppCompatActivity() { @Inject lateinit var people:People override fun onCreate(savedInstanceState: Bundle?) {  super.onCreate(savedInstanceState)  setContentView(R.layout.activity_home)  DaggerHomeComponent.builder()    .build()    .inject(this)//會在這句代碼時執(zhí)行注入的操作  people.hello() }}03-01 14:30:23.425 3256-3256/? I/System.out: hello//大功告成

當(dāng)然,上面這種只是最簡單的用法,如果需要傳入一些非自定義類的實例就不適用了,畢竟你不能在第三方的類中加入@Inject注解。此時就需要用到@Module和@Provides注解。

@Module

用來標(biāo)記類,為Component提供依賴,相當(dāng)于告訴Component,如果需要依賴可以來找我,當(dāng)然前提是在Component中配置了該Module。同時Module可以通過includes依賴其他的Module。

@Provides

用來標(biāo)記Module中的方法,該方法的返回類型是你需要提供的依賴類型。

舉個自己項目中的例子,我需要在presenter中創(chuàng)建一個pl2303對象,pl2303對象的創(chuàng)建又需要context和pl2303Interface,所以我們需要提供三個依賴,因為context在其他地方也要用,我們單獨提出來:

@Moduleclass ContextModule(private var mContext: Context) { @Provides fun getContext() = mContext}

pl2303Interface只有這一個地方要用:

@Module(includes = arrayOf(ContextModule::class))class Pl2303Module(private var pl2303Interface: ActivityCallBridge.PL2303Interface) { @Provides fun providePl2303(mContext: Context): Pl2303 {  return Pl2303(mContext, pl2303Interface) }}

其中includes可以是多個,我們這里把ContextModule加進(jìn)來,這樣創(chuàng)建pl2303就只差一個pl2303Interface,這是個接口對象,不能new,從構(gòu)造函數(shù)注入進(jìn)來。接下來創(chuàng)建注射器:

@Component(modules = arrayOf(Pl2303Module::class))interface MainPresenterComponent { fun inject(presenter: MainPresenter)}

最后注入:

class MainPresenter(val view: MainContract.View) : MainContract.Presenter, ActivityCallBridge.PL2303Interface, LifecycleObserver { @Inject lateinit var pl2303: Pl2303 init {  DaggerMainPresenterComponent.builder()    .contextModule(ContextModule(view.context))    .pl2303Module(Pl2303Module(this))    .build()    .inject(this) }}

如果在大型項目中,一個Component有很多的Module,那么不需要傳入?yún)?shù)的Module是可以省略的,看一下官方的注釋文檔:

public static void main(String[] args) {  OtherComponent otherComponent = ...;  MyComponent component = DaggerMyComponent.builder()   // required because component dependencies must be set(必須的)   .otherComponent(otherComponent)   // required because FlagsModule has constructor parameters(必須的)   .flagsModule(new FlagsModule(args))   // may be elided because a no-args constructor is visible(可以省略的)   .myApplicationModule(new MyApplicationModule())   .build();  }

@Named和@Qualifier

@Named是@Qualifier的一個實現(xiàn)。有時候我們會需要提供幾個相同類型的依賴(比如繼承于同一父類),如果不做處理的話編譯器就不知道我們需要的具體是哪一個依賴而報錯,比如這樣:

abstract class Animalclass Dog : Animal() { override fun toString(): String {  return "dog" }}class Cat : Animal() { override fun toString(): String {  return "cat" }}@Moduleclass AnimalModule { @Provides fun provideDog(): Animal = Dog() @Provides fun provideCat(): Animal = Cat()}data class Pet @Inject constructor(val pet: Animal)

這時候就需要標(biāo)記一下來告訴編譯器我們需要的是哪個依賴:

@Moduleclass AnimalModule { @Provides @Named("dog") fun provideDog(): Animal = Dog() @Provides @Named("cat") fun provideCat(): Animal = Cat()}data class Pet @Inject constructor(@Named("dog") val pet: Animal)

上面我們說了@Named只是@Qualifier的一個實現(xiàn)而已,所以我們也可以用@Qualifier來達(dá)到一樣的效果,實際使用中也更推薦使用@Qualifier的方式,因為@Named需要手寫字符串來進(jìn)行標(biāo)識,容易出錯。

使用@Qualifier需要注意:

  • 創(chuàng)建一個自定義的Qualifier至少需要@Qualifier, @Retention(RUNTIME)這兩個注解。
  • 可以有自己的屬性。

我們可以看一下@Named的源碼來加深一下理解:

@Qualifier@Documented@Retention(RUNTIME)public @interface Named { /** The name. */ String value() default "";}

下面我們比葫蘆畫瓢來改造一下上面的例子:

@Moduleclass AnimalModule { @Provides @DogAnim fun provideDog(): Animal = Dog() @Provides @CatAnim fun provideCat(): Animal = Cat()}@Qualifier@Retention(AnnotationRetention.RUNTIME)annotation class DogAnim@Qualifier@Retention(AnnotationRetention.RUNTIME)annotation class CatAnimdata class Pet @Inject constructor(@CatAnim val pet: Animal)

經(jīng)測試依然是可以運行的。

Pet(pet=cat)

@Scope和@Singleton

A scope annotation applies to a class containing an injectable constructor and governs how the injector reuses instances of the type

@Scope是用來標(biāo)記包含可注入構(gòu)造函數(shù)的類或者提供注入依賴對象的類,簡單來說,可以用來標(biāo)記包含@Inject構(gòu)造函數(shù)的類或者@Module類。

@Scope是用來管理依賴的生命周期的。它和@Qualifier一樣是用來自定義注解的,而@Singleton和@Named類似,是@Scope的默認(rèn)實現(xiàn)。

如果一個注射器和創(chuàng)建依賴對象的地方?jīng)]有標(biāo)記@Scope,那么每次注入時都會創(chuàng)建一個新的對象,如果標(biāo)記了@Scope,則在規(guī)定的生命周期內(nèi)會使用同一個對象,特別注意是在規(guī)定的生命周期內(nèi)單例,并不是全局單例,或者可以理解為在@Component內(nèi)單例。

還是借助上面的例子:

data class People constructor(val name: String) { @Inject constructor() : this("Tom") init {  println("init:$name") } @Inject fun hello(){  println("hello:$name") }}class HomeActivity : AppCompatActivity() { @Inject lateinit var people: People @Inject lateinit var people_2: People override fun onCreate(savedInstanceState: Bundle?) {  super.onCreate(savedInstanceState)  setContentView(R.layout.activity_home)  DaggerHomeComponent.builder()    .build()    .inject(this)  println("people===people_2:${people===people_2}") }}

運行結(jié)果:

people===people_2:false

說明確實是兩個不同的對象,接下來我們改造一下:

@Singletondata class People constructor(val name: String) { ...//和之前一樣}@Singleton@Component(modules = arrayOf(AnimalModule::class))interface HomeComponent { fun inject(activity: HomeActivity)}...//HomeActivity代碼和之前一樣

再次看下運行結(jié)果:

people===people_2:true

說明這次兩次都是訪問的同一個對象。上面提到這只是一個局部單例,那么怎么實現(xiàn)一個全局單例呢,很簡單,只要保證標(biāo)記的Component在全局只初始化一次即可,比如在Application中初始化,篇幅限制代碼就不貼了,有興趣的騷年可以自己實踐一下。

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對VeVb武林網(wǎng)的支持。


注:相關(guān)教程知識閱讀請移步到kotlin教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 鹤岗市| 吉安市| 遵化市| 杭锦后旗| 漳浦县| 邵阳市| 黑水县| 宜城市| 大洼县| 井陉县| 德安县| 徐水县| 华容县| 宣威市| 长沙县| 秭归县| 万盛区| 平遥县| 银川市| 财经| 丽江市| 平阳县| 介休市| 潜江市| 昌图县| 栾城县| 卢湾区| 泰州市| 称多县| 南涧| 昌乐县| 平远县| 绩溪县| 桃源县| 玉田县| 新兴县| 措美县| 游戏| 巴林右旗| 耒阳市| 泉州市|