简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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