Java 是否可以在@Provides顶部使用自定义注释而不是@Named?
假设我们想要Java 是否可以在@Provides顶部使用自定义注释而不是@Named?,java,dependency-injection,annotations,inversion-of-control,guice,Java,Dependency Injection,Annotations,Inversion Of Control,Guice,假设我们想要@注入字符串。我创建模块: public class StringModule extends AbstractModule{ @Provides String black() { return "black"; } @Provides String white() { return "white" } } 现在我要求注入值: @Inject private String wantWhiteHere;
@注入字符串。我创建模块
:
public class StringModule extends AbstractModule{
@Provides
String black() {
return "black";
}
@Provides
String white() {
return "white"
}
}
现在我要求注入值:
@Inject
private String wantWhiteHere;
显然,Guice会抛出错误,因为绑定不明确。我知道如果我使用名为
的注释,我可以得到白色
:
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"
}
}
可能吗?当我这样做时,例外情况是:
已创建到java.lang.String的绑定
配置的
有什么地方我可以配置来实现它吗
我的Guice版本是使用@限定符
是的,这是可能的。确保您具有以下声明:
@javax.inject.Qualifier
@Target({ FIELD, PARAMETER, METHOD })
@Retention(RUNTIME)
public @interface White { }
你可以在Guice的官方维基上找到
@javax.inject.Qualifier
@Target({ FIELD, PARAMETER, METHOD })
@Retention(RUNTIME)
public @interface White { }