Guice:构建相关的物体树/机器人腿
我有一个 A 类,它包含一个 B 类,如下所示:
class A {
private final B b;
@Inject
A(B b) {
this.b = b;
}
}
interface B {}
class B1 implements B {}
class B2 implements B {}
class Client() {
@Inject
Client(@AhasB1 A aHasB1, @AhasB2 A aHasB2) { }
}
我想绑定两个不同的 A,一个带注释的 @AhasB1
,另一个带注释的 @AhasB2
。我怎样才能正确绑定这些?
I have a class A that holds a class B like this:
class A {
private final B b;
@Inject
A(B b) {
this.b = b;
}
}
interface B {}
class B1 implements B {}
class B2 implements B {}
class Client() {
@Inject
Client(@AhasB1 A aHasB1, @AhasB2 A aHasB2) { }
}
I'd like to bind two different A's, one annotated @AhasB1
and another @AhasB2
. How can I bind these correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下是我使用
PrivateModule
完成此操作的方法。Here's how I did it using
PrivateModule
.不要使用
@Provides
方法,而是考虑一组Provider
类型(可能嵌套在类型 A 中),从而授予您对私有 ctor 的访问权限。或者使其成为受包保护的 ctor,并将提供程序放在与其相同的包中。或者,当然,您可以将模块类型移动到与 A 相同的包中。另一个选择是 AssistedInject,它允许您指定一组方法,这些方法将根据名称或参数返回不同的实例(在您的情况下,可能是 A 的子类型)。我认为它将可以访问私有构造函数。
最后一个想法:为什么不将 A 的构造函数保留为公共,以便库的用户可以手动注入依赖项?如果这仅供内部使用,记录 ctor 也足够了。
Instead of using
@Provides
methods, consider a set ofProvider<A>
types, possibly nested in the type A, granting you access to the private ctor. Or make it a package-protected ctor, and put the providers in the same package as it. Or, of course, you could move your Module type into the same package as A.Another option would be AssistedInject, which would allow you to specify a set of methods that would, based on name or param, would return different instances (in your case, probably subtypes of A). I think it will have access to private constructors.
One last thought for you: Why not leave the constructor to A as public, so that a user of the library can manually inject dependencies? If this is for internal use only, documenting the ctor could also suffice.
我认为您正在寻找的解决方案是 Private Modules
expose(A.class).annotatedWith(B1.class)
http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/PrivateModule.html
-dg
I think the solution you are looking for is Private Modules
expose(A.class).annotatedWith(B1.class)
http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/PrivateModule.html
-dg