如何将特定参数绑定到自定义注释的实例? [英] How do I bind a specific parameter to an instance of a custom annotation?
问题描述
如何使用Guice进行以下工作?
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);
}
}
推荐答案
可能最简单的方法是使用@Provides
方法:
Probably the simplest way to do this would be to use @Provides
methods:
@Provides @HelpTopicId("A")
protected String provideA() {
return "1";
}
或者,您可以创建HelpTopicId
批注/接口的可实例化实现,类似于Names.named
的实现(请参见
Alternatively, you could create an instantiable implementation of the HelpTopicId
annotation/interface similar to the implementation of Names.named
(see NamedImpl). Be aware that there are some special rules for how things like hashCode()
are implemented for an annotation... NamedImpl
follows those rules.
此外,使用new TypeLiteral<String>(){}
是浪费的... String.class
可以代替它使用.此外,对于String
,int
等,通常应使用bindConstant()
而不是bind(String.class)
.它更简单,要求您提供绑定注释,并且仅限于原语,String
,Class
文字和enum
s.
Also, using new TypeLiteral<String>(){}
is wasteful... String.class
could be used in its place. Furthermore, for String
, int
, etc. you should typically use bindConstant()
instead of bind(String.class)
. It's simpler, requires that you provide a binding annotation, and is limited to primitives, String
s, Class
literals and enum
s.
这篇关于如何将特定参数绑定到自定义注释的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!