为什么我的@singleton不起作用?

时间:2009-10-26 08:43:21

标签: java singleton guice

我在尝试@Singleton of Guice时遇到了一个问题:

import com.google.inject.Singleton;

@Singleton
public class ConfigManager {
    private String data;

    public void setData(String data) {
        this.data = data;
    }

    public String getData(){
        return this.data;
    }

    public static void main(String[] args){
        ConfigManager config1 = Guice.createInjector().getInstance(ConfigManager.class);
        ConfigManager config2 = Guice.createInjector().getInstance(ConfigManager.class);
        config1.setData("data");
        System.out.println(config2.getData());
    }

} 

为什么这个简单的样本总是打印为空?

1 个答案:

答案 0 :(得分:8)

单身人士是注射器的全球,而不是JVM。您需要稍微调整一下代码:

 Injector injector = Guice.createInjector();
 ConfigManager config1 = injector.getInstance(ConfigManager.class);
 ConfigManager config2 = injector.getInstance(ConfigManager.class);