繁体   English   中英

Guice:类或实例级别的绑定批注

[英]Guice: class- or instance-level binding annotations

Guice提供了两种变体,即所谓的绑定注释 ,它们似乎可以分解为类和实例级别的注释:

“班级”:

bind(Service.class).annotatedWith(Red.class).to(RedServiceImpl.class);

@Red
public class SomeService implements Service { ... }

Service redSvc = injector.getInstance(SomeService.class);

“实例级”:

bind(Service.class).annotatedWith(Names.named("Blue").to(BlueServiceImpl.class);
@Blue blueSvc = injector.getInstance(Service.class);

一种方法何时优先于另一种方法? 看来,类级别的注释比实例级别的注释更加绝对/不灵活。 哪种方法的优点/缺点/缺点?

我不确定我是否理解您的问题。 您对绑定注释的使用是不规则的。 通常,您不会注释局部变量或类,而会注释字段和参数。

您的第一个代码示例将使注入器返回SomeService,但这不是因为您的注释或绑定,而是因为SomeService是一个具体的实现。 您是否已要求这样做:

Service redSvc = injector.getInstance(Service.class);

您将得到一个错误:

1) No implementation for com.example.Service was bound.
  while locating com.example.Service

您的第二个示例也不正确。 如果使用“ Names定义绑定,则必须使用@Named访问该绑定。 使用@Blue将导致编译器错误。 正确的用法是@Named(value="Blue")

绑定注释的常见最佳做法是:

@BindingAnnotation
@Target({ FIELD, PARAMETER, METHOD })
@Retention(RUNTIME)
public @interface MyAnno

在这种情况下,这两个都是编译错误:

@Red // not allowed
public class SomeService implements Service { ... }

@Blue // not allowed
blueSvc = injector.getInstance(Service.class);

唯一的实际区别是,在一种情况下,您绑定了整个注释,而在另一种情况下,您绑定了具有特定参数的注释。 并非所有注释都带有参数,在这种情况下,与注释类的绑定是完全正常的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM