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

眉间皱痕 提交于 2019-12-02 02:44:58

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/17493143/guice-how-to-get-instance-of-singleton-without-injector-or-using-constructor-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!