Guice:如何获得没有注射器或使用构造器注入的Singleton的实例 [英] Guice: How to get instance of Singleton without injector or using Constructor Injection

查看:113
本文介绍了Guice:如何获得没有注射器或使用构造器注入的Singleton的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单例类定义为:

  @Singleton 
class MySingletonClass {
。 ...
}

我有另一个类使用这个单例类,但这个类有使用新的操作符创建。因此,我不能使用构造函数注入或setter注入等。

  class MyClass {
public void method(){
//使用MySingletonClass
}
}

我可以肯定将这个实例传递给MyClass的构造函数,但是从我的程序的上下文中不太好设计。



另一个解决方案是创建一个静态getInstance方法为MySingletonClass,以便我可以从程序中的任何地方获取实例。但是我想知道Guice是否支持类似的东西?我确定Guice可以允许在任何地方获取单例实例。



非常感谢。

解决方案>

我认为如果myClass需要MySingletonClass,这意味着它们之间存在明确的依赖关系,因此一个正确的解决方案是将MySingletonClass的实例传递给MyClass的构造函数。



构造函数注入是最理想的注入方法之一,因为它使依赖性显式,并阻止创建不满足依赖关系的MyClass。
如果您真的不喜欢构造函数注入,您可以随时使用setter注入,您可以手动注入MySingletonClass的实例。


I have got an singleton class defined as:

@Singleton
class MySingletonClass{
   ....
}

I have another class which uses this singleton Class but this class has to be created using new operator. Thus I cannot use constructor injection or setter injection etc.

class MyClass {
   public void method() {
       // Uses instnace of MySingletonClass
   }
}

I can certainly pass an instance of this into the constructor of MyClass but it does not quite a good design from the context of my program.

Another solution will be to create an static getInstance method for MySingletonClass so that I can get instance from anywhere in the program. But I want to know if Guice supports anything similar to this? I am sure Guice can allow getting singleton instance anywhere.

Many thanks.

解决方案

I think that if myClass needs the MySingletonClass, this means that there is a clear dependency between them, and hence a correct solution is to pass the instance of MySingletonClass to the constructor of MyClass.

The constructor injection is one of the the most desirable injection methods since it makes the dependency explicit and prevent the creation of MyClass with unsatisfied dependencies. If you really don't like the constructor injection, you can always use a setter injection where you can manually inject the instance of MySingletonClass.

这篇关于Guice:如何获得没有注射器或使用构造器注入的Singleton的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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