Java 8 Guice按需注入
我一直在学习Guice。我看到有按需注射 我想知道它的用途和一些例子。我有一个场景,从conf文件中读取一组属性。那里没有注射。稍后,我想将这些属性中的同一个config类实例注入到其他一些类中Java 8 Guice按需注入,java-8,guice,playframework-2.5,Java 8,Guice,Playframework 2.5,我一直在学习Guice。我看到有按需注射 我想知道它的用途和一些例子。我有一个场景,从conf文件中读取一组属性。那里没有注射。稍后,我想将这些属性中的同一个config类实例注入到其他一些类中 class Props { //set of properties read from a config file to this class } Props props = readProperties(); // instance of this class having all the
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;
}
在这种情况下,是否可以使用Guice的按需注入?我还使用Play框架的conf文件来加载模块文件。
play.modules.enabled+=com.example.mymodule加载模块中的属性,并通过
bindConstant
加载属性。如果要使用(类道具的)非常相同的配置实例,可以将其实例绑定为。这当然不是唯一的解决办法,但对我来说是有意义的
以下是一个例子:
定义提供程序:
public class PropsProvider implements Provider<Props>
{
@Override
public Props get()
{
...read and return Props here...
}
}
注入您的配置:
@Inject
public Connection(Props props) {
this.props = props;
}
您可以在文档中阅读:
单件最适用于:
- 有状态对象,如配置或计数器
- 构造或查找成本较高的对象
- 占用资源的对象,例如数据库连接池
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
}
}
嗨,我有个问题。我本想使用提供商,但我得到了一个以前的道具参考,我现在无法阅读。所以我只是想知道,当我得到它时,是否可以注入它的引用,并在我使用它的任何地方进一步使用它。根据您的上下文,有多种解决方案。不幸的是,我不熟悉这出戏。但是上面的单例是惰性的(在需要之前不会实例化)-这意味着您仍然可以使用具有内部状态的提供程序-例如,您可以在模块定义中使用相同的提供程序实例,并且在读取道具的地方,只需在同一共享实例上调用类似provider.setProps(道具)的东西。这听起来很肮脏:-)
@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
}
}