作为身份函数实现的 Guice-Provider 如何工作?
How does a Guice-Provider implemented as an identity function work?
我正在尝试了解以下提供商:
@Provides
@ScopeMatching
@MatchingScopeAnnotation
MatchingBag provideBag(MatchingBag bag) {
return bag;
}
引用注解的声明如下:
@BindingAnnotation
@Target({ FIELD, PARAMETER, METHOD })
@Retention(RUNTIME)
public @interface ScopeMatching {
// nothing
}
@ScopeAnnotation
@Target({ TYPE, METHOD })
@Retention(RUNTIME)
private @interface MatchingScopeAnnotation {
// nothing
}
定义一个只是身份函数的提供者看起来很奇怪。我可以看到删除提供程序会导致注入错误,因此很重要。
能否请您帮我了解提供程序的作用是什么?解决供应商不是先有鸡还是先有蛋的问题吗? Guice 是怎么做到的?
对于 Guice 来说,@ScopeMatching MatchingBag
与不合格的 MatchingBag
是完全不同的密钥。剥离后,您可以将其视为类似于 @Provides A provideA(AImpl impl) { return impl; }
.
Guice 的行为类似于 Map<Key, Provider>
,其中 Key 是具有可选绑定注释的限定类型。您在这里有一个自定义绑定注释 ScopeMatching
,带有适当的元注释 @BindingAnnotation
。因此,通过您询问的绑定,两个键(不合格的 MatchingBag
和 @ScopeMatching MatchingBag
)都可以通过您的对象图获得,其中前者总是 returns 一个新实例,而后者 returns MatchingScopeAnnotation
范围内的一个实例(根据您的范围实现,它可能是一个新实例,也可能是一个 saved/cached 实例)。
您的 "identity" 绑定等同于可能更易识别的 bind
版本:
bind(MatchingBag.class).annotatedWith(ScopeMatching.class)
.to(MatchingBag.class)
.in(MatchingScopeAnnotation.class);
...或者等价地,甚至更清楚:
bind(Key.get(MatchingBag.class, ScopeMatching.class))
.to(Key.get(MatchingBag.class))
.in(MatchingScopeAnnotation.class);
在 Guice docs on Binding Annotations 中查看更多信息。
我正在尝试了解以下提供商:
@Provides
@ScopeMatching
@MatchingScopeAnnotation
MatchingBag provideBag(MatchingBag bag) {
return bag;
}
引用注解的声明如下:
@BindingAnnotation
@Target({ FIELD, PARAMETER, METHOD })
@Retention(RUNTIME)
public @interface ScopeMatching {
// nothing
}
@ScopeAnnotation
@Target({ TYPE, METHOD })
@Retention(RUNTIME)
private @interface MatchingScopeAnnotation {
// nothing
}
定义一个只是身份函数的提供者看起来很奇怪。我可以看到删除提供程序会导致注入错误,因此很重要。
能否请您帮我了解提供程序的作用是什么?解决供应商不是先有鸡还是先有蛋的问题吗? Guice 是怎么做到的?
对于 Guice 来说,@ScopeMatching MatchingBag
与不合格的 MatchingBag
是完全不同的密钥。剥离后,您可以将其视为类似于 @Provides A provideA(AImpl impl) { return impl; }
.
Guice 的行为类似于 Map<Key, Provider>
,其中 Key 是具有可选绑定注释的限定类型。您在这里有一个自定义绑定注释 ScopeMatching
,带有适当的元注释 @BindingAnnotation
。因此,通过您询问的绑定,两个键(不合格的 MatchingBag
和 @ScopeMatching MatchingBag
)都可以通过您的对象图获得,其中前者总是 returns 一个新实例,而后者 returns MatchingScopeAnnotation
范围内的一个实例(根据您的范围实现,它可能是一个新实例,也可能是一个 saved/cached 实例)。
您的 "identity" 绑定等同于可能更易识别的 bind
版本:
bind(MatchingBag.class).annotatedWith(ScopeMatching.class)
.to(MatchingBag.class)
.in(MatchingScopeAnnotation.class);
...或者等价地,甚至更清楚:
bind(Key.get(MatchingBag.class, ScopeMatching.class))
.to(Key.get(MatchingBag.class))
.in(MatchingScopeAnnotation.class);
在 Guice docs on Binding Annotations 中查看更多信息。