Guice:在这种情况下,如何在模块中配置@Provides和@Singleton? [英] Guice: how do you configure an @Provides and @Singleton in a module in this case?
问题描述
我在带有@Provides
注释的模块中有一个提供者方法:
I have a provider method in a module annotated with @Provides
:
@Provides
public ChatServicePerformanceMonitor getChatServicePerfMon() {
...
}
,并且用@Singleton
注释了ChatServicePerformanceMonitor
.在我使用此实例的代码中,我无法让guice被动地"注入它,因为我正在使用的框架正在构造封闭类(它不使用Guice,所以这是我知道的唯一方法以获得参考):
and I have annotated my ChatServicePerformanceMonitor
with @Singleton
. In my code, where I use this instance, I can't have guice "passively" inject it, due to a framework I'm using that's constructing the enclosing class (it does not use Guice, so this is the only way I know of to get the reference):
chatServicePerfMon = injector.getInstance(ChatServicePerformanceMonitor.class);
看来Guice不尊重我的ChatServicePerformanceMonitor
类上的@Singleton
批注.每次调用jector.getInstance(ChatServicePerformanceMonitor.class)都会得到一个实例.
It seems Guice does not respect the @Singleton
annotation on my ChatServicePerformanceMonitor
class. I get an instance for every call to injector.getInstance(ChatServicePerformanceMonitor.class).
将@Singleton
添加到provider方法似乎可以解决此问题:
Adding the @Singleton
to the provider method seems to fix this:
@Provides @Singleton
public ChatServicePerformanceMonitor getChatServicePerfMon() {
...
}
这是预期的行为吗?看来实例上的@Singleton
应该是我所需要的.
Is that the expected behavior? It seems an @Singleton
on the instance should be all I would need.
推荐答案
如果要像这样创建ChatServicePerformanceMonitor
:
@Provides
public ChatServicePerformanceMonitor getChatServicePerfMon() {
return new ChatServicePerformanceMonitor();
}
然后,您的课程级别@Singleton
注释将无效,因为Guice不会创建对象,而是您会创建. Guice只能在其创建的对象上强制作用域.将@Singleton
添加到getChatServicePerfMon()
方法没有什么问题.
then your class level @Singleton
annotation will have no effect because Guice isn't creating the object, you are. Guice can only enforce scope on objects it creates. There's nothing wrong with adding @Singleton
to your getChatServicePerfMon()
method.
如果在ChatServicePerformanceMonitor
类上具有无参数的构造函数(或@Inject
构造函数),并且删除了@Provides
方法,则对注入器的连续调用将返回相同的单例.
If you have a no-argument constructor (or an @Inject
constructor) on the ChatServicePerformanceMonitor
class and you remove your @Provides
method then continual calls to the injector will return the same singleton.
这篇关于Guice:在这种情况下,如何在模块中配置@Provides和@Singleton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!