Java – how to test Guice singleton?
•
Java
Guice singletons is strange to me
First of all, I thought
IService ser = Guice.createInjector().getInstance(IService.class); System.out.println("ser=" + ser); ser = Guice.createInjector().getInstance(IService.class); System.out.println("ser=" + ser);
Will work as a single person, but it will return
ser=Service2@1975b59 ser=Service2@1f934ad
Never mind, it's not easy
Injector injector = Guice.createInjector(); IService ser = injector.getInstance(IService.class); System.out.println("ser=" + ser); ser = injector.getInstance(IService.class); System.out.println("ser=" + ser);
Working as a single person
ser=Service2@1975b59 ser=Service2@1975b59
Therefore, I need to have the static field of injector (singleton for singletons)
How do I pass it to the module for testing?
Solution
When using Guice, each JVM should create only one injector Typically, you will create it at the entry point of your application (that is, in your public static void main method) If createinjector is called multiple times in the application, Guice error may be used!
Singles are examples of every syringe Note that this is not every JVM instance The best way to get singles' references is to inject it Another way is to ask for a unique syringe instance for you
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码