我想像这样在Guice中绑定Set:
public class TestModule extends AbstractModule {
@Override
protected void configure() {
Set<String> testSet = Sets.newHashSet("Hello", "World");
bind(Set.class).annotatedWith(Named.named("Test.Set")).toInstance(testSet);
}
}
我已确保在创建注射器时包含此模块。我稍后尝试使用此绑定集:
public class TestClass {
@Inject
public NewReleaseRunner(@Named("Test.Set") Set<String> testSet) {
System.out.println(testSet.toString());
}
}
但是,这会导致失败:No implementation for java.util.Set<java.lang.String> annotated with @com.google.inject.name.Named(value=Test.Set) was bound.
我担心的是Set<String>
是通用的,但是绑定是绑定到Set.class
的。我该怎么做才能解决此问题?
答案 0 :(得分:3)
我认为您有两种选择。替换
bind(Set.class).annotatedWith(Named.named("Test.Set")).toInstance(testSet);
使用
bind(new TypeLiteral<Set<String>>() {}).annotatedWith(Named.named("Test.Set")).toInstance(testSet);
或或删除模块的configure()
绑定,而是添加
@Provides
@Named("Test.Set")
public Set<String> stringSet() {
return Sets.newHashSet("Hello", "World");
}