How to test Guice Singleton?

Guice singletons are strange to me

At 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 like singleton but returns

ser=Service2@1975b59
ser=Service2@1f934ad

its ok, it should not 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 like singleton

ser=Service2@1975b59
ser=Service2@1975b59

So I need to have a static field with an injector (Singleton for Singletons)

how can i go to it? Module for testing?

+3
source share
2 answers

When using Guice, you must create exactly one injector per JVM. Usually you will create it at the entry point of the application (i.e., into your method public static void main). If you call createInjectorseveral times in your application, you may be mistaken in using Guice!

. , JVM. - . - .

+12

( ), , , . Guice singleton .

? singleton GoF - , , static . singleton , , .

, singleton Guice:

public class myModule extends AbstractModule {
    protected void configure() {
        bind(Service.class).to(ServiceImpl.class).in(Singleton.class);
    }
}

Guice , , - . Injector.

0

Source: https://habr.com/ru/post/1746664/


All Articles