Java 这是在guice中使用自定义注释的正确方法吗?
嗨,我在guice中有一个自定义注释Java 这是在guice中使用自定义注释的正确方法吗?,java,dependency-injection,guice,Java,Dependency Injection,Guice,嗨,我在guice中有一个自定义注释 @BindingAnnotation @Retention(RetentionPolicy.RUNTIME) @Target({TYPE}) public @interface Worker { String value(); } 现在,如果 bind(Base.class) .annotatedWith(Test1.class.getAnnotation(Worker.class)) .to(Test1.class); bind
@BindingAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE})
public @interface Worker {
String value();
}
现在,如果
bind(Base.class)
.annotatedWith(Test1.class.getAnnotation(Worker.class))
.to(Test1.class);
bind(Base.class)
.annotatedWith(Test2.class.getAnnotation(Worker.class))
.to(Tes2.class);
如果我尝试从喷油器中获取相应的实例,比如
injector.getInstance(Key.get(Worker.class, new WorkerImpl("worker1")));
injector.getInstance(Key.get(Worker.class, new WorkerImpl("worker2")));
这些会给我worker1和worker2的例子吗
我不确定这是否是正确的方法。如果您有自定义注释,您应该正确地实现它 例如,您有
@Worker
注释,但WorkerImpl
实现了@Named
。你应该让它实现@Worker
现在,您的绑定应该如下所示:
bind(Base.class)
.annotatedWith(new WorkerImpl("worker1"))
.to(Test1.class);
bind(Base.class)
.annotatedWith(new WorkerImpl("worker2"))
.to(Test2.class);
您将得到如下实例:
Base test1 = injector.getInstance(Key.get(Base.class, new WorkerImpl("worker1")));
Base test2 = injector.getInstance(Key.get(Base.class, new WorkerImpl("worker2")));
对于其余部分,您可以正确处理注释hashCode,这是创建自定义注释实现的最困难部分
bind(Base.class)
.annotatedWith(new WorkerImpl("worker1"))
.to(Test1.class);
bind(Base.class)
.annotatedWith(new WorkerImpl("worker2"))
.to(Test2.class);
Base test1 = injector.getInstance(Key.get(Base.class, new WorkerImpl("worker1")));
Base test2 = injector.getInstance(Key.get(Base.class, new WorkerImpl("worker2")));