java - Guice:类或实例级绑定(bind)注释

标签 java dependency-injection guice

Guice 提供了所谓的绑定(bind)注释的两种变体,它们似乎真正分解为类级和实例级注释:

“类(class)级别”:

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);

什么时候一种方法优先于另一种方法?看起来类级注释比实例级注释更加绝对/不灵活。这两种方法的优点/缺点/注意事项/陷阱?

最佳答案

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

您的第一个代码示例将导致注入(inject)器返回 SomeService,但不是因为您的注释或绑定(bind),而是因为 SomeService 是一个具体的实现。如果您要求这样做:

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

你会得到一个错误:

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

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

绑定(bind)注释的常见最佳实践是这样的:

@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);

关于java - Guice:类或实例级绑定(bind)注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10141646/

相关文章:

java - 将 Spring Security 添加到现有的 Spring AngularJS 应用程序

java - 是否有可能破坏 CDI 示波器?

java - 为什么不调用 Eclipse 插件处理程序?

c# - 如何注入(inject)表示文件夹集合的依赖项?

inheritance - Java & Guice - 如何处理继承和抽象?

java - Spring Cloud Netflix eureka 服务器 - tomcat 启动时出错

java - 谷歌吉斯。使用 Java EE5 时注入(inject) EJB

c# - 如何使用每个实现的附加参数/信息实现接口(interface)

session - Apache Wicket 口 : Injecting dependencies in Session (using Guice)

java - 使用 ActorSystem 和 Guice 时停止时出现异常