如何在HK2中将多个接口收集到一个Collection中? [英] How to collect several interfaces into a Collection in HK2?
问题描述
我有我的AbstractBinder
,我用相同的接口绑定了几个类.假设我绑定了都实现Animal
接口的Fish
和Cat
.
I have my AbstractBinder
and I bind several classes with the same interface. Let's say I bind Fish
and Cat
which both implement Animal
interface.
将它们注入采用Collection<Animal>
的bean中最简单/正确的方法是什么?
What is the easiest/proper way of injecting them into a bean which takes Collection<Animal>
?
PS:Spring在@Autowire List<Animal>
中具有等效功能,并且集合由Spring创建和填充.
PS: Spring has equivalent in simply @Autowire List<Animal>
and the collection is created and populated by Spring.
推荐答案
HK2 has IterableProvider<T>
, as mentioned here in the documentation. You can get the service by name, by qualifier annotation, or just iterate over them, as it's an Iterable
. Just for fun, here is a test.
public class IterableProviderTest {
public static interface Service {}
public static class ServiceOne implements Service {}
@QualAnno
public static class ServiceTwo implements Service {}
@Qualifier
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public static @interface QualAnno {
public static class Instance
extends AnnotationLiteral<QualAnno> implements QualAnno {
public static QualAnno get() {
return new Instance();
}
}
}
public class Binder extends AbstractBinder {
@Override
protected void configure() {
bind(ServiceOne.class).to(Service.class).named("one");
bind(ServiceTwo.class).to(Service.class).qualifiedBy(QualAnno.Instance.get());
}
}
@Inject
private IterableProvider<Service> services;
@Test
public void test_IterableProvider() {
ServiceLocator locator = ServiceLocatorUtilities.bind(new Binder());
locator.inject(IterableProviderTest.this);
assertEquals(2, services.getSize());
Service serviceOne = services.named("one").get();
assertTrue(serviceOne instanceof ServiceOne);
Service serviceTwo = services.qualifiedWith(QualAnno.Instance.get()).get();
assertTrue(serviceTwo instanceof ServiceTwo);
}
}
更新
对于List<Service>
(避免使用HK2 InterablProvider),我唯一想到的就是使用Factory
并将IterableProvider
注入其中,然后从中返回列表.例如
UPDATE
For a List<Service>
(to avoid HK2 InterablProvider), the only think I can think of is to use a Factory
and inject the IterableProvider
into it, and from there return the list. For example
public class Binder extends AbstractBinder {
@Override
protected void configure() {
...
bindFactory(ListServiceFactory.class).to(new TypeLiteral<List<Service>>(){});
}
}
public static class ListServiceFactory implements Factory<List<Service>> {
@Inject
private IterableProvider<Service> services;
@Override
public List<Service> provide() {
return Lists.newArrayList(services);
}
@Override
public void dispose(List<Service> t) {}
}
是的,这需要一些额外的工作.
Yeah it's a little bit of extra work.
这篇关于如何在HK2中将多个接口收集到一个Collection中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!