java - 是否可以在@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
解决方案
利用@Qualifier
对的,这是可能的。确保您有以下声明:
@javax.inject.Qualifier
@Target({ FIELD, PARAMETER, METHOD })
@Retention(RUNTIME)
public @interface White { }
您可以在 Guice 的官方 wiki 上找到更多信息。
推荐阅读
- c++ - 扩展类及其数据成员
- mysql - AWS RDS 上的 MySQL init_file
- r - 最大似然估计如何在 R 的 rugarch 包中发生?
- reactjs - TypeError:无法读取未定义的 React js 的属性“值”
- flutter - NoSuchMethodError:在 null 上调用了 getter 'firstName'。Receiver:null 尝试调用:firstName 单击注册按钮时出现此错误
- python-3.x - Max 返回错误的答案
- git - 从 Git 存储库中删除的文件保留在 Jenkins 工作区中
- android - 显示底部卡片 CardStackView
- c# - main.cs(35,34):错误 CS1041:需要标识符,“in”是关键字
- vue.js - 从 Vue.js 中的内部方法更新数组时不调用 v-for