简体   繁体   English

Guice:如何在没有注入器或不使用构造函数注入的情况下获取Singleton实例

[英]Guice: How to get instance of Singleton without injector or using Constructor Injection

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. 我还有另一个使用此单例类的类,但必须使用new运算符创建该类。 Thus I cannot use constructor injection or setter injection etc. 因此,我不能使用构造函数注入或setter注入等。

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. 我当然可以将其实例传递给MyClass的构造函数,但从我的程序上下文来看,它并不是一个很好的设计。

Another solution will be to create an static getInstance method for MySingletonClass so that I can get instance from anywhere in the program. 另一个解决方案是为MySingletonClass创建静态getInstance方法,以便可以从程序中的任何位置获取实例。 But I want to know if Guice supports anything similar to this? 但是我想知道Guice是否支持类似的功能? I am sure Guice can allow getting singleton instance anywhere. 我确信Guice可以在任何地方获取单例实例。

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. 我认为,如果myClass需要MySingletonClass,则意味着它们之间存在明显的依赖关系,因此正确的解决方案是将MySingletonClass的实例传递给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. 构造函数注入是最理想的注入方法之一,因为它可以使依赖关系显式显示并防止创建具有不满意依赖关系的MyClass。 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. 如果您真的不喜欢构造函数注入,则可以始终使用setter注入,在其中可以手动注入MySingletonClass的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM