简体   繁体   中英

How to test Guice Singleton?

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 main method). If you call createInjector multiple 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.

You really need to do a little more testing (and reading) before making wild, inaccurate accusations like that. I'm using Guice to manage my singleton instances just fine.

What do your module bindings look like? The singleton pattern in the GoF is simply a way of ensuring that there is one instance of a class, but the use of static makes it actually a bad choice. The need for a singleton is that there is only one instance of a class available while the application is running.

The following is all that is needed to create a singleton instance using Guice:

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

When you ask Guice to give you the instance, you'll get the same instance unless you do some unique scoping yourself. Per default, the singleton will be for the current Injector instance.

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