Guice Singletons are weird for me
First I thought that
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 singleton, but it returns
ser=Service2@1975b59
ser=Service2@1f934ad
its ok, it doesnt have to be 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);
works as singleton
ser=Service2@1975b59
ser=Service2@1975b59
So i need to have static field with Injector(Singleton for Singletons)
how do i pass to it Module for testing?
When using Guice, you should create exactly one injector per JVM. Usually you’ll create it in your application’s entry point (ie. in your
public static void mainmethod). If you callcreateInjectormultiple times in your application, you may be using Guice wrong!Singletons are instance-per-injector. Note that this is not instance-per-JVM. The best way to obtain a reference to a singleton is to be injected with it. The other way is to ask the one and only injector instance to give it to you.