学习Dagger2笔记:【5】@Qualifier

目录

0. 前言
1. 依赖与注入
2. @Inject
3. @Module & @Provides
4. @Component
5. @Qualifier
6. Provider & Lazy
7. @Scope
8. 注入到Set和Map容器
9. Bind系列注解
10. dagger中依赖关系与继承关系
11. dagger.android

dagger与抽象

继承、封装和多态是面向对象的三大特征,这三大特征无一不是围绕着抽象这个词展开的,但在前几篇的例子中,我们的依赖都是具体的类型,比如ComputerCPUMemory严重违反了依赖倒置原则

模块间的依赖通过抽象发生,实现类之间不发生直接的依赖关系,其依赖关系是通过接口或抽象类产生的

总之,我们接下来需要加上抽象的思想,看看dagger怎样处理

新增需求

现在我们将Computer改为一个抽象类,并且派生出两个子类:WindowsComputerLinuxComputer,而Activity中需要依赖这两种Computer,并显示它们的信息,改动如下:

// 将Computer改为抽象类
abstract class Computer(private val os: String, private val price: Int) {
   
    @set:Inject lateinit var cpu: CPU
    @set:Inject lateinit var memory: Memory

    init {
   
        // 通常在非final类的构造函数中应避免传递this、调用非final方法等,因为父类构造函数先于子类执行,此时调用一些被子类重写的方法可能产生错误。不过这里是对父类中的依赖进行注入,所以Suppress了
        @Suppress("LeakingThis") 
        DaggerComputerComponent
            .builder()
            .memoryModule(MemoryModule(8192))
            .build()
            .inject(this)
    }

    fun execute(builder: StringBuilder) {
    // CPU执行时除了返回自身信息,还要将CPU和Memory的信息一并返回
        builder.append("Computer OS: ").append(os).append("\n")
        builder.append("Computer Price: ").append(price).append("\n")
        cpu.execute(builder)
        memory.execute(builder)
    }
}

// 写好两个派生类
class WindowsComputer(price: Int) : Computer("Windows", price)
class LinuxComputer(price: Int
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Kotlin中,@Qualifier注解通常用于与依赖注入框架一起使用,以标识特定的依赖项。在使用依赖注入框架时,您可以使用@Qualifier注解来指定要注入的依赖项的特定实现。 以下是一个简单的示例,演示如何使用@Qualifier注解: ```kotlin interface MyDependency class MyFirstDependency : MyDependency { override fun toString(): String { return "MyFirstDependency" } } class MySecondDependency : MyDependency { override fun toString(): String { return "MySecondDependency" } } class MyComponent { @Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class FirstDependency @Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class SecondDependency @Inject @FirstDependency lateinit var firstDependency: MyDependency @Inject @SecondDependency lateinit var secondDependency: MyDependency } fun main(args: Array<String>) { val component = DaggerMyComponent.builder().build() println(component.firstDependency) // prints "MyFirstDependency" println(component.secondDependency) // prints "MySecondDependency" } ``` 在上面的示例中,我们定义了一个MyDependency接口,然后实现了两个具体的实现MyFirstDependency和MySecondDependency。接下来,我们定义了一个MyComponent类,其中包含了@FirstDependency和@SecondDependency注解来标识要注入的特定依赖项。最后,我们使用Dagger2库生成MyComponent实例,并打印出注入的依赖项。 请注意,@Qualifier注解本身并不提供任何特定的注入功能,而只是用于标识特定的依赖项。实际的注入功能由依赖注入框架提供。在上面的示例中,我们使用了Dagger2库来实现依赖注入

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值