[英]Getting a guice object at runtime with an annotation?
I have a provider: 我有一个提供者:
@SuppressWarnings({ "rawtypes", "unchecked" })
@Provides
@Singleton
@OutboundBroker
public EventBroker outboundBrokerProvider()
At runtime, I want to get this one. 在运行时,我想得到这个。
EventBroker outbound=injector.getInstance(Key.get(EventBroker.class, Names.named("OutboundBroker")));
However, this code doesn't work -- the provider isn't named, but I can't figure out how to retrieve it using the annotation @OutboundBroker 但是,此代码不起作用 - 提供程序未命名,但我无法弄清楚如何使用注释@OutboundBroker检索它
Key.get(EventBroker.class, OutboundBroker.class)
It's extremely rare to need to get more than one object from the Injector
. 极少需要从Injector
获取多个对象。 If you use pure dependency-injection, your main()
method (or your container) creates the injector and gets one object, and one or more methods on that object are called. 如果使用纯依赖注入,则main()
方法(或容器)创建注入器并获取一个对象,并调用该对象上的一个或多个方法。 That one object would be injected with what it needs. 一个对象将被注入它需要的东西。
So you can do this: 所以你可以这样做:
class EventService {
private final EventBroker outboundEventBroker;
@Inject
private EventService(
@OutboundBroker EventBroker outboundBroker) {
this.outboundEventBroker = outboundBroker;
}
...
}
As Jeff Bowman stated, this assumes that OutboundBroker
is itself annotated with @BindingAnnotation
. 正如Jeff Bowman所说,这假设OutboundBroker
本身用@BindingAnnotation
注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.