Guice: How to get instance of Singleton without in

2019-02-26 00:30发布

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条回答
我只想做你的唯一
2楼-- · 2019-02-26 01:12

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.

查看更多
登录 后发表回答