Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 这是在guice中使用自定义注释的正确方法吗?_Java_Dependency Injection_Guice - Fatal编程技术网

Java 这是在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

嗨,我在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(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")));