2015-10-18 85 views
1

我有這樣的吉斯代碼爲什麼Guice會爲我的單身人士創建一個新實例?

public class MainModule extends AbstractModule { 

    @Override 
    protected void configure() { 
    bind(GlobalSettings.class).toProvider(GlobalSettingsProvider.class).in(Singleton.class); 
} 

public class GlobalSettingsProvider implements Provider<GlobalSettings> { 

    @Override 
    public GlobalSettings get() { 

     GlobalSettings globalSettings = new GlobalSettings(); 
     globalSettings.isDummyRun = Boolean.parseBoolean(System.getProperty("isDummyRun", "false")); 
     globalSettings.inputFlavor = System.getProperty("input_flavor", "none"); 
    } 
} 

public class A(){ 

    public A() { 
     this.injector = Guice.createInjector(new MainModule()); 
injector.getInstance(IHttpClientReRunWrapper.class); 
     globalSettings = injector.getInstance(GlobalSettings.class); 

    resultsComparerRunner1 = injector.getInstance(ResultsComparerRunner.class); 
    resultsComparerRunner2 = injector.getInstance(ResultsComparerRunner.class); 
    resultsComparerRunner3 = injector.getInstance(ResultsComparerRunner.class); 
    } 
} 

public class ResultsComparerRunner(){ 

public class ResultsComparerRunner(){ 
initStaticFromInjector(); 
} 

    private void initStaticFromInjector() { 
     routingResponseShortRepository = injector.getInstance(IRoutingResponseShortRepository.class); 
     globalSettings = injector.getInstance(GlobalSettings.class); //verify only one injector per run 
    } 

爲什麼我在instanc看到globalSettingsAResultsComparerRunner的實例是不同的?

我想這是singelton

回答

6

我很好奇提供商的結合加上單的行爲,所以我根據你的代碼中創建一個測試 - gist

@Test 
public void execute() { 
    Injector injector = Guice.createInjector(new AbstractModule() { 
     @Override 
     protected void configure() { 
      bind(GlobalSettings.class).toProvider(GlobalSettingsProvider.class).in(Singleton.class); 
     } 
    }); 

    GlobalSettings g1 = injector.getInstance(GlobalSettings.class); 
    GlobalSettings g2 = injector.getInstance(GlobalSettings.class); 

    assertThat(g1).isSameAs(g2); 
} 

結果:綠色。這意味着你的模塊設置正在工作,你的問題必須在別的地方。你如何將注入器傳遞給ResultsComparerRunner?這真的是包含singleton定義的注入器嗎?

2

我的問題是,我在兩個不同的地方 -

它創造了兩個單身人士稱爲

injector = Guice.createInjector(new MainModule());

兩次。

相關問題