views:

124

answers:

1

Hi, I met a problem when trying @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());
    }

}

Why this simple sample always print null?

+6  A: 

Singletons are global to the injector, not to the JVM. You'll want to tweak your code ever-so-slightly:

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