首页 > 解决方案 > 是否可以在@Provides 顶部使用自定义注释而不是@Named?

问题描述

假设我们想要@Inject字符串。我创建Module

public class StringModule extends AbstractModule{
    @Provides
    String black() {
        return "black";
    }

    @Provides
    String white() {
        return "white"
    }
}

现在我要求注入的值:

@Inject
private String wantWhiteHere;

显然 Guice 会抛出一个错误,因为绑定是不明确的。我知道white如果我使用这样的@Named注释我可以得到:

public class StringModule extends AbstractModule{
    @Named("black")
    @Provides
    String black() {
        return "black";
    }

    @Named("white")
    @Provides
    String white() {
        return "white"
    }
}

接着:

@Named("white")
@Inject
private String iGotWhiteHere;

但我想要的是这样的:

public class StringModule extends AbstractModule{
    @Black
    @Provides
    String black() {
        return "black";
    }

    @White
    @Provides
    String white() {
        return "white"
    }
}

.

@White
@Inject
private String tryingToGetWhiteHere;

可能吗?当我这样做时,例外:

已配置到 java.lang.String 的绑定...

有什么地方可以配置来实现它吗?

我的 Guice 版本是4.2.3

标签: javadependency-injectionannotationsinversion-of-controlguice

解决方案


利用@Qualifier

对的,这是可能的。确保您有以下声明:

@javax.inject.Qualifier
@Target({ FIELD, PARAMETER, METHOD })
@Retention(RUNTIME)
public @interface White { }

您可以在 Guice 的官方 wiki 上找到更多信息。


推荐阅读