简体   繁体   English

如何测试Guice Singleton?

[英]How to test Guice Singleton?

Guice Singletons are weird for me Guice Singletons对我来说很奇怪

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) 所以我需要有Injector的静态字段(Singleton for Singletons)

how do i pass to it Module for testing? 我如何传递给它模块进行测试?

When using Guice, you should create exactly one injector per JVM. 使用Guice时,每个JVM应该只创建一个注入器。 Usually you'll create it in your application's entry point (ie. in your public static void main method). 通常,您将在应用程序的入口点(即在您的public static void main方法中)创建它。 If you call createInjector multiple times in your application, you may be using Guice wrong! 如果在应用程序中多次调用createInjector ,则可能使用Guice错误!

Singletons are instance-per-injector. 单身人士是每个注射器的实例。 Note that this is not instance-per-JVM. 请注意,这不是每个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. 我正在使用Guice来管理我的单例实例。

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. GoF中的单例模式只是确保一个类的一个实例的一种方式,但static的使用使它实际上是一个糟糕的选择。 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: 以下是使用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. 当您要求Guice为您提供实例时,除非您自己做一些独特的范围,否则您将获得相同的实例。 Per default, the singleton will be for the current Injector instance. 默认情况下,单例将用于当前的Injector实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM