如果仅注入直接依赖项,如何防止 Google Guice 中的循环引用
Google Guice 的最佳做法是仅注入直接依赖项。 但如果我使用以下示例代码,如何在类 Customer 中创建帐户实例?
@Provides
Account providePurchasingAccount(Customer customer) {
return customer.getPurchasingAccount();
}
问题是,Guice 总是尝试通过调用 providePurchasingAccount() 来获取新的 Account,这会导致循环引用。
a best practice in Google Guice is to Inject Only Direct Dependencies.
But if I use the following example code, how could I create an instance of account in class Customer?
@Provides
Account providePurchasingAccount(Customer customer) {
return customer.getPurchasingAccount();
}
The problem is, that Guice always try to get a new Account by calling providePurchasingAccount(), which results in a circular references.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您摘录的方法位于 CustomersModule 类中,而不是 Customer 类中。
这里有更多细节。
这取决于客户的绑定方式。
在 Guice wiki 页面中,您提到它不显示客户的绑定。
想象一下模块也有这个方法。
在这种情况下,当首先注入 Account 时,会调用此方法来获取 Customer 对象,然后调用 ProvidePurchasingAccount 来获取 Account。
The method you excerpt is in the class CustomersModule, not Customer.
Here is more detail.
This depends on how Customer is bound.
In the Guice wiki page you mention it doesn't show the binding for Customer.
Imagine the module also has this method.
In that case, when Account is injected first this method is called to get the Customer object then providePurchasingAccount is called to get the Account.