英文:
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<String> provideLinkedBlockingQueue() {
return new LinkedBlockingQueue<>();
}
In another class I attempted to grab an instance this way:
public class Resource {
private final LinkedBlockingQueue<String> bufferQueue;
@Inject
public Resource(LinkedBlockingQueue<String> 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<String> 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<LinkedBlockingQueue<String>>
or TypeLiteral<LinkedBlockingQueue<String>>
instead of LinkedBlockingQueue.class
.
For instance:
injector.getProvider(new Key<LinkedBlockingQueue<String>>(){}).get();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论