2017-04-11 42 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