如何将特定参数绑定到自定义注释的实例?
如何使用 Guice 完成以下工作?
// The Guice Module configuration
void configure() {
// The following won't compile because HelpTopicId is abstract.
// What do I do instead?
bind(new TypeLiteral<String>(){}).
annotatedWith(new HelpTopicId("A")).toInstance("1");
bind(new TypeLiteral<String>(){}).
annotatedWith(new HelpTopicId("B")).toInstance("2");
}
public @interface HelpTopicId {
public String helpTopicName();
}
public class Foo {
public Foo(@HelpTopicId("A") String helpTopicId) {
// I expect 1 and not 2 here because the actual parameter to @HelpTopicId is "A"
assertEquals(1, helpTopicId);
}
}
How do I make the following work using Guice?
// The Guice Module configuration
void configure() {
// The following won't compile because HelpTopicId is abstract.
// What do I do instead?
bind(new TypeLiteral<String>(){}).
annotatedWith(new HelpTopicId("A")).toInstance("1");
bind(new TypeLiteral<String>(){}).
annotatedWith(new HelpTopicId("B")).toInstance("2");
}
public @interface HelpTopicId {
public String helpTopicName();
}
public class Foo {
public Foo(@HelpTopicId("A") String helpTopicId) {
// I expect 1 and not 2 here because the actual parameter to @HelpTopicId is "A"
assertEquals(1, helpTopicId);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许最简单的方法是使用
@Provides
方法:或者,您可以创建
HelpTopicId
注释/接口的可实例化实现,类似于的实现>Names.named
(请参阅NamedImpl)。请注意,对于如何为注释实现hashCode()
等内容有一些特殊规则...NamedImpl
遵循这些规则。另外,使用
new TypeLiteral(){}
是浪费...可以使用String.class
来代替它。此外,对于String
、int
等,您通常应该使用bindConstant()
而不是bind(String.class).它更简单,要求您提供绑定注释,并且仅限于基元、
String
、Class
文字和enum
。Probably the simplest way to do this would be to use
@Provides
methods:Alternatively, you could create an instantiable implementation of the
HelpTopicId
annotation/interface similar to the implementation ofNames.named
(see NamedImpl). Be aware that there are some special rules for how things likehashCode()
are implemented for an annotation...NamedImpl
follows those rules.Also, using
new TypeLiteral<String>(){}
is wasteful...String.class
could be used in its place. Furthermore, forString
,int
, etc. you should typically usebindConstant()
instead ofbind(String.class)
. It's simpler, requires that you provide a binding annotation, and is limited to primitives,String
s,Class
literals andenum
s.构造函数
Foo(String)
必须使用@Inject
进行注释。您应该尝试使用 Guice
Named
注释,而不是使用您自己的HelpTopicId
注释。如果您想推出自己的
@Named
接口实现,请查看包中的 Guice 实现com.google.inject.name
。Constructor
Foo(String)
has to be annotated with@Inject
.Instead of using your own
HelpTopicId
annotation, you should try with GuiceNamed
annotation.If you want to roll out your own implementation of
@Named
interface, take a look at the Guice's implementation in the packagecom.google.inject.name
.