Guice:注入带有自己参数的构造函数的类吗? [英] Guice: Inject class with constructor with own parameters?
问题描述
我对Guice有问题.我想举一个例子来说明这一点.我想始终动态传递此构造函数的参数,例如新测试("bob",765);.我还希望Guice注入一些字段(例如此处SomeOtherObject).我怎样才能做到这一点?预先感谢!
I have a problem with Guice. I would like to show this with an example. I want to pass the parameters of this constructor always dynamically, so e.g. new Test("bob", 765);. I also want some fields (like here SomeOtherObject) to be injected by Guice. How can I do this? Thanks in advance!
public class Test {
private String name;
private int id;
//Needs to be injected by Guice
@Inject
SomeOtherObject object;
public Test(String name, int id) {
this.name = name;
this.id = id;
}
}
推荐答案
Guice的 AssistedInject 功能是处理此问题的好方法.
Guice's AssistedInject feature is a good way to handle this.
基本上,您定义工厂以使用以下方法获取 Test
对象:
Basically you define a factory to get Test
objects with:
public interface TestFactory {
public Test create(String name, int id);
}
使用 @Assisted
批注扩展 Test
类的 @Inject
构造函数:
Augment the Test
class's @Inject
constructor with @Assisted
annotation:
public class Test {
@Inject
public Test(SomeOtherObject object, @Assisted String name, @Assisted int id) {
this.object = object;
this.name = name;
this.id = id;
}
}
然后在模块的配置中使用 FactoryModuleBuilder
:
And then use FactoryModuleBuilder
in your Module's configure:
install(new FactoryModuleBuilder().build(TestFactory.class));
而不是直接构造 Test
s,而是注入 TestFactory
并使用它来创建 Test
s:
And instead of constructing Test
s directly, inject a TestFactory
and use it to create Test
s:
public class OtherThing {
@Inject
TestFactory factory;
public Test doStuff(Stirng name, int id) {
return factory.create(name, id);
}
}
注意:现在看文档,看来 AutoFactory 具有被引入作为实现此操作的首选方法,并且可能会更简单.
Note: looking at the docs now, it appears that AutoFactory has been introduced as the preferred way to do this, and may be simpler.
这篇关于Guice:注入带有自己参数的构造函数的类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!