Guice:Binding 带有属性的注释

Guice:Binding Annotations with Attributes

现在正在看Guice的官方文档,但是对Binding Annotation章节有一些疑问

This 解释 "Annotation with Attributes"。但是,我不确定这个解释。

Binding Annotations with Attributes

Guice supports binding annotations that have attribute values. In the rare case that you need such an annotation:

Create the annotation @interface. Create a class that implements the annotation interface. Follow the guidelines for equals() and hashCode() specified in the Annotation Javadoc. Pass an instance of this to the annotatedWith() binding clause.

我不明白那个解释。解释的目的是什么?我学习了@Paypal(在本文档中)和@name 两个注解。但是当我想对同一个class使用两个以上的依赖时,也许我们不能只用这两个注释来实现? 现在我很困惑,谁能解释一下?

Guice 通过使用 Key, which is just a name for the combination of a binding annotation (an annotation that itself is annotated with @BindingAnnotation or @Qualifier) 和 a 类型(如果需要,使用参数)找出您想要注入的内容。这些都是有效的密钥,彼此不同:

  • YourClassOne
  • YourClassTwo
  • List<Integer>
  • List<String>
  • @Paypal YourClassOne
  • @Paypal YourClassTwo
  • @YourBindingAnnotation YourClassOne
  • @YourBindingAnnotation List<String>

但是,允许注释具有属性,如 @Named("your name here")。这意味着键不仅在您拥有的绑定注释上有所不同,而且在其属性上也有所不同。让我们使用带有属性 的 注释向上面的列表添加一些键:

  • @Named("foo") YourClassOne
  • @Named("bar") YourClassOne
  • @AnotherBindingAnnotation(foo=3, bar=5) YourClassOne
  • @AnotherBindingAnnotation(foo=6, bar=1) YourClassOne

它们各不相同,它们都是提供给 Guice 并从 Guice 注入的有效东西。

通常,您可能不需要创建自己的带有属性的绑定注释: 绑定注释一开始并不常见,大多数情况下您需要它们可以用空的 (no-attribute) 绑定注释或使用 built-in @Named 注释(及其对应的 Names.named, which helps you create a compatible instance of your annotation that you can use in your AbstractModule). However, if you DO want to create your own binding annotation with attributes, you can use the part of the docs you quoted in order to create that, particularly in conforming to the Annotation.equals and Annotation.hashCode requirements. (If this is something you expect to do a lot, consider using a library like Apache Commons AnnotationUtils or a code generator like Google Auto's AutoAnnotation.)

来处理