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

前端 未结 1 2023
名媛妹妹
名媛妹妹 2021-01-22 14:19

I have got an singleton class defined as:

@Singleton
class MySingletonClass{
   ....
}

I have another class which uses this singleton Class but

相关标签:
1条回答
  • 2021-01-22 14:27

    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.

    0 讨论(0)
提交回复
热议问题