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/