【发布时间】:2011-10-03 22:51:08
【问题描述】:
关于 Guice 的问题。我还在学习它,但我可以理解基本原理。
这个问题已经在网上被问过几次了,但从来没有一个具体的答案(我找不到)。
假设我遇到了图片上的情况(网上也有类似的例子)。
public class Dog {}
public class Walk implements Walkable {
private final Dog dog;
private final boolean leash;
@Inject
public Walk(Dog dog, @Assisted boolean leash) {
this.dog = dog;
this.leash = leash;
}
public void go() {
}
}
public interface Walkable {
void go();
}
public interface WalkFactory {
Walk create(boolean leash);
}
public class AssistedMain {
public static void main(String[] args) {
Injector i = Guice.createInjector(new AbstractModule() {
protected void configure() {
install(new FactoryModuleBuilder().
implement(Walkable.class, Walk.class).
build(WalkFactory.class));
}
});
Walk walk = i.getInstance(WalkFactory.class).create(true);
}
}
这一切都很好。但问题是——我能否以某种方式将该对象实例重新注入到“容器”(注入器)中,以便在依赖此依赖项的类上使用。
所以,让我们添加一个interface Person、class PersonImpl。
新的类来源是:
public interface Person {
void walkDog();
}
public class PersonImpl implements Person {
private Walkable walkable;
@Inject
public PersonImpl(Walkable walkable) {
this.walkable = walkable;
}
public void setWalkable(Walkable walkable) {
this.walkable = walkable;
}
public void walkDog() {
walkable.go();
}
}
所以,问题是——我是否能够以某种方式将这个特定实例实际注入到添加的对象中。这是一个简单的例子,但我们可以假设在这个之下有 10 级类。
我找到的解决方案不是很灵活。比如:
Injector i = Guice.createInjector(new SimpleModule(false, dog));
然后绑定到具体实例。这不是很动态。基本上,每次我需要不同的运行时/动态参数时,我都必须重新创建注入器。
Provider<T> 很好,FactoryModuleBuilder 有帮助,但我怎样才能将对象注入回去?
这个问题有更多动态的解决方案吗?
谢谢。
【问题讨论】: