Dagger2自定义@Qualifier用法 [英] Dagger2 custom @Qualifier usage

查看:393
本文介绍了Dagger2自定义@Qualifier用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在制造汽车并且我有几个具有不同实施的制动豆

Suppose I'm building a car and I have several Brake beans with different implementations

class Car {
    @Inject
    Car(@BrakeType(value="abs")Brake frontBrake, @BrakeType(value="nonabs")Brake rearBrake) { }
}

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface BrakeType {
    String value();
}

interface Brake {}

@BrakeType(value="abs")
class AbsBrakeImpl implements Brake {
    @Inject AbsBrakeImpl() {}
}

@BrakeType(value="nonabs")
class BrakeImpl implements Brake {
    @Inject BrakeImpl() {}
}

为什么我的CarModule必须为特定的Brake类型定义@Provides?自定义注释类型@BrakeType不应该足以确定要注入哪个impl?或者是否需要使用反射,dagger2不使用?

why does my CarModule have to define @Provides for the specific Brake types? Shouldn't the custom annotation type @BrakeType be enough to determine which impl to inject? Or would that require using reflection, which dagger2 does not use?

@Module
public class CarModule {
    @Provides @BrakeType("abs")
    public Brake absBrake() {
        return new AbsBrakeImpl();
    }
    @Provides @BrakeType("nonabs")
    public Brake nonabsBrake() {
        return new BrakeImpl();
    }
}


推荐答案

Dagger不会在类上查看限定符注释,只能在 @Provides @Binds 方法上查看。所以你班上的 @BrakeType(value =abs)注释没有任何效果。

Dagger doesn't look at qualifier annotations on classes, only on @Provides or @Binds methods. So the @BrakeType(value="abs") annotations on your classes don't have any effect.

编写代码的更规范的方法是:

A more canonical way of writing your code is:

class AbsBrakeImpl implements Brake {
    @Inject AbsBrakeImpl() {}
}

class BrakeImpl implements Brake {
    @Inject BrakeImpl() {}
}

@Module
abstract class CarModule {
    @Binds @BrakeType("abs")
    abstract Brake absBrake(AbsBrakeImpl impl);

    @Binds @BrakeType("nonabs")
    abstract Brake nonabsBrake(BrakeImpl impl);
}

请注意,因为你有 @Inject 在你的实现的构造函数上,你可以简单地使用Dagger的 @Bind 将实现直接绑定到适当的限定接口。

Note that since you have @Inject on the constructors of your implementations, you can simply use Dagger's @Bind to bind the implementations directly to the appropriately qualified interface.

这篇关于Dagger2自定义@Qualifier用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆