0

我在尝试 @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());
    }

} 

为什么这个简单的示例总是打印 null?

4

1 回答 1

8

单例对于注入器是全局的,而不是 JVM。你会想要稍微调整你的代码:

 Injector injector = Guice.createInjector();
 ConfigManager config1 = injector.getInstance(ConfigManager.class);
 ConfigManager config2 = injector.getInstance(ConfigManager.class);
于 2009-10-26T16:14:44.640 回答