Guice:在这种情况下,如何在模块中配置@Provides和@Singleton? [英] Guice: how do you configure an @Provides and @Singleton in a module in this case?

查看:350
本文介绍了Guice:在这种情况下,如何在模块中配置@Provides和@Singleton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在带有@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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆