访问来自注入器的Guice单例

huangapple go评论57阅读模式
英文:

Accessing a Guice singleton from Injector

问题

我正在使用Guice在Java应用程序中创建一个单例。我在模块类中使用了以下方法:

@Provides
@Singleton
public LinkedBlockingQueue<String> provideLinkedBlockingQueue() {
    return new LinkedBlockingQueue<>();
}

在另一个类中,我尝试通过以下方式获取实例:

public class Resource {
  private final LinkedBlockingQueue<String> bufferQueue;

  @Inject
  public Resource(LinkedBlockingQueue<String> bufferQueue) {
    this.bufferQueue = bufferQueue;
  }

最后,我希望从我的注入器中访问应用程序中的相同实例,我尝试以以下方式实现:

LinkedBlockingQueue<String> bufferQueue =
        injector.getProvider(LinkedBlockingQueue.class).get();

这是在Resource类和我的应用程序中从注入器共享实例的正确方法吗?

英文:

I'm using Guice to create a singleton in a Java application. I used the following method in my module class:

@Provides
@Singleton
public LinkedBlockingQueue&lt;String&gt; provideLinkedBlockingQueue() {
    return new LinkedBlockingQueue&lt;&gt;();
  }

In another class I attempted to grab an instance this way:

public class Resource {
  private final LinkedBlockingQueue&lt;String&gt; bufferQueue;

  @Inject
  public Resource(LinkedBlockingQueue&lt;String&gt; bufferQueue) {
    this.bufferQueue = bufferQueue;
  }

Finally, I want to access the same instance in my application from my injector and I tried to do that this way:

LinkedBlockingQueue&lt;String&gt; bufferQueue =
        injector.getProvider(LinkedBlockingQueue.class).get();

Is this the correct way to go about sharing an instance between the Resource class and in my application from my injector?

答案1

得分: 2

以下是翻译好的内容:

这样在资源类和我的应用程序之间共享实例的方式是否正确?

不,不正确。

你应该使用 Key<LinkedBlockingQueue<String>> 或者 TypeLiteral<LinkedBlockingQueue<String>> 替代 LinkedBlockingQueue.class

例如:

injector.getProvider(new Key<LinkedBlockingQueue<String>>(){}).get();
英文:

> Is this the correct way to go about sharing an instance between the Resource class and in my application from my injector?

No, it is not.

You should use Key&lt;LinkedBlockingQueue&lt;String&gt;&gt; or TypeLiteral&lt;LinkedBlockingQueue&lt;String&gt;&gt; instead of LinkedBlockingQueue.class.

For instance:

injector.getProvider(new Key&lt;LinkedBlockingQueue&lt;String&gt;&gt;(){}).get();

huangapple
  • 本文由 发表于 2020年9月20日 02:25:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63972045.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定