我正在阅读Guice文档,并且遇到了标记为
Eliminate the Cycle (Recommended)的部分,这引起了我的兴趣,因为这正是导致我今天获得文档的问题.
基本上,为了消除循环依赖关系,您可以“将依赖关系案例提取到一个单独的类中”.好的,那里没什么新鲜的.
所以,在这个例子中,我们有.
public class Store {
private final Boss boss;
private final CustomerLine line;
//...
@Inject public Store(Boss boss, CustomerLine line) {
this.boss = boss;
this.line = line;
//...
}
public void incomingCustomer(Customer customer) { line.add(customer); }
}
public class Boss {
private final Clerk clerk;
@Inject public Boss(Clerk clerk) {
this.clerk = clerk;
}
}
public class Clerk {
private final CustomerLine line;
@Inject Clerk(CustomerLine line) {
this.line = line;
}
void doSale() {
Customer sucker = line.getNextCustomer();
//...
}
}
您有一个商店和一个职员,每个人都需要引用一个CustomerLine实例.这个概念没有问题,并且经典的依赖注入很容易实现:
CustomerLine customerLine = new CustomerLine();
Clerk clerk = new Clerk(customerLine);
Boss boss = new Boss(clerk);
Store store = new Store(boss, customerLine);
这很容易,但是现在,我需要使用Guice注射器来做到这一点.因此,我的问题是实施以下内容:
you may want to make sure that the Store and Clerk both use
the same CustomerLine instance.
是的,这正是我想要做的.但是我如何在Guice模块中做到这一点?
public class MyModule extends AbstractModule implements Module {
@Override
protected void configure() {
//Side Question: Do I need to do this if there if Boss.class is the implementation?
bind(Boss.class);
bind(CustomerLine.class).to(DefaultCustomerLine.class); //impl
}
}
我用我的模块创建了一个注入器:
Injector injector = Guice.createInjector(new MyModule());
现在,我想要一个Store实例:
Store store = injector.getInstance(Store.class);
这会将CustomerLine和Boss的新实例注入此Store实例.然而,Boss获得了一个Clerk实例,它也会注入一个CustomerLine实例.此时,它将是一个新实例,与注入Store的实例不同.
问题重新审视
> Store和Clerk如何按此顺序共享同一个实例,
不使用@Singleton?
如果需要更多信息,请告诉我,或者这个问题没有明确说明,我一定会修改.