Java Guice在不使用@Singleton的情况下将单个实例注入多个对象
我在阅读Guice文档时,遇到了一个标签为的部分,它激发了我的兴趣,因为正是这个问题让我今天看到了文档 基本上,为了消除循环依赖,您“将依赖项情况提取到一个单独的类中。”好的,这里没有什么新内容 所以,在这个例子中,我们有Java Guice在不使用@Singleton的情况下将单个实例注入多个对象,java,guice,cyclic-dependency,Java,Guice,Cyclic Dependency,我在阅读Guice文档时,遇到了一个标签为的部分,它激发了我的兴趣,因为正是这个问题让我今天看到了文档 基本上,为了消除循环依赖,您“将依赖项情况提取到一个单独的类中。”好的,这里没有什么新内容 所以,在这个例子中,我们有 public class Store { private final Boss boss; private final CustomerLine line; //... @Inject public Store
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注入来实现这一点。因此,我的问题是实施以下内容:
您可能需要确保商店和店员都使用
相同的CustomerLine实例
是的,这正是我想做的。但是在Guice模块中如何做到这一点呢
我用我的模块创建了一个喷油器:
Injector injector = Guice.createInjector(new MyModule());
现在,我想要一个Store
的实例:
Store store = injector.getInstance(Store.class);
这将把CustomerLine
和Boss
的新实例注入到Store
的这个实例中<但是,code>Boss会获取Clerk
的一个实例,该实例也会被注入CustomerLine
的一个实例。此时,它将是一个新实例,与注入存储的实例不同
重提问题
Store
和Clerk
如何在此序列中共享同一实例,
不使用@Singleton
请告诉我是否需要更多信息,或者这个问题说明得不够清楚,我一定会修改。您应该使用
公共类StoreProvider实现提供程序{
@注入
私人老板;
公共商店{
返回新店(boss,boss.getClerk().getCustomerLine());
}
}
然后将其绑定到模块中
bind(Store.class).toProvider(StoreProvider.class)代码>这很有道理!谢谢我认为应该是类商店提供商**实现**提供商
@BayStallion Fixed:)谢谢!如果需要添加构造函数值,该怎么办?
Store store = injector.getInstance(Store.class);
public class StoreProvider implements Provider<Store> {
@Inject
private Boss boss ;
public Store get() {
return new Store(boss, boss.getClerk().getCustomerLine());
}
}