2017-04-11 69 views
1

我一直在學習Guice。我看到有一個按需注入hereGuice按需注射

我想知道它的用途和一些例子。我有一個場景,我從conf文件中讀取一組屬性。那裏沒有注射。後來我想將這些屬性的配置類的相同實例注入其他類。

class Props { 
    //set of properties read from a config file to this class 

} 

Props props = readProperties(); // instance of this class having all the properties but not put into injection container 

在連接類我想用它的注射後來

@Inject 
public Connection(Props props) { 
    this.props = props; 
} 

是否可以使用按需噴射吉斯在這種情況下?另外我使用Play框架的conf文件來加載我的模塊文件。 play.modules.enabled + = com.example.mymodule

回答

3

如果你希望使用同樣的配置實例(類道具),你可以結合你的模塊,並將它們在屬性的實例作爲singletonprovider binding。這當然不是唯一的解決方案,但它對我來說很有意義。

下面是一個例子:

定義提供商:

public class PropsProvider implements Provider<Props> 
{ 
    @Override 
    public Props get() 
    { 
     ...read and return Props here... 
    } 
} 

使用供應商在單範圍綁定:

bind(Props.class).toProvider(PropsProvider.class).in(Singleton.class); 

注入你的配置:

@Inject 
public Connection(Props props) { 
    this.props = props; 
} 

你可以 讀取的文檔中:

單身是最有用的:

  • 狀態的對象,例如配置或計數器
  • 對象是構建或查找
  • 對象佔用資源昂貴,如數據庫連接池。

也許你的配置對象匹配的第一個和第二個標準。我會避免從模塊內讀取配置。看看爲什麼here

我在幾個單元測試用例中使用了按需注入,我希望在測試中的組件中注入模擬依賴關係,並使用了字段注入(這就是爲什麼我儘量避免域注入:-))和I出於某些原因,優選不使用InjectMocks

這裏有一個例子:

組件:

class SomeComponent 
{ 
    @Inject 
    Dependency dep; 

    void doWork() 
    { 
     //use dep here 
    } 
} 

測試本身:

@RunWith(MockitoJUnitRunner.class) 
public class SomeComponentTest 
{ 
    @Mock 
    private Dependency mockDependency; 

    private SomeComponent componentToTest; 

    @Before 
    public void setUp() throws Exception 
    { 
     componentToTest = new SomeComponent(); 

     Injector injector = Guice.createInjector(new AbstractNamingModule() 
     { 
      @Override 
      protected void configure() 
      { 
       bind(Dependency.class).toInstance(mockDependency); 
      } 
     }); 

     injector.injectMembers(componentToTest); 
    } 

    @Test 
    public void test() 
    { 
     //test the component and/or proper interaction with the dependency 
    } 

} 
+0

嗨,我有一個查詢。我本來希望使用Provider,但是我從之前得到了對Props的參考,現在我無法讀取它。所以我只是想知道我是否可以在獲得它時注入參考,並在任何地方使用Injector。 –

+0

根據您的情況有多種解決方案。不幸的是我不熟悉Play FW。但是......上面的單例是懶惰的(直到需要時纔會被實例化) - 這意味着你仍然可以使用具有內部狀態的提供者 - 例如你可以在你的模塊定義中使用相同的提供者實例,並且在你閱讀道具的地方只需在同一個共享實例上調用諸如provider.setProps(props)之類的東西。這聽起來很骯髒:-) –

1

負載通過bindConstant