我正在try 实现一个简单的应用程序使用Guice for DI. 这款应用程序有一个界面Shape:

public interface Shape {
    void draw();
}

这是由班级Rectangle实现的.

public class Rectangle implements Shape{
    @Override
    public void draw() {
        System.out.printf("Shape is a rectangle");
    }
}

然后是一个ShapeRequest类,它将根据我提供的显式绑定在运行时注入Shape个Bean.

@Singleton
public class ShapeRequest {

    @AnnotatedRectangle
    private final Shape shape;

    @Inject
    public ShapeRequest(Shape shape) {
        System.out.println("Attempting injection");
        this.shape = shape;
    }

    public Shape getShape() {
        return shape;
    }

    public void action(){
        System.out.println(shape.getClass());
        shape.draw();
    }
}

绑定类(实现AbstractModule)如下:

@Override
protected void configure(){
    bind(Shape.class).annotatedWith(AnnotatedRectangle.class).to(Rectangle.class);
    bind(String.class).annotatedWith(Color.class).toInstance("GREEN");

}

为了支持以上内容,我创建了一个注释:

@BindingAnnotation
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotatedRectangle {
}

现在,在客户机类中:

Injector injector = Guice.createInjector(new AppModule());
ShapeRequest request=injector.getInstance(ShapeRequest.class);

错误:

Exception in thread "main" com.google.inject.ConfigurationException: Guice configuration errors:

1) [Guice/MissingImplementation]: No implementation for Shape was bound.

Did you mean?
    * Shape annotated with interface AnnotatedRectangle bound at AppModule.configure(AppModule.java:18)

Requested by:
1  : ShapeRequest.<init>(ShapeRequest.java:19)
      \_ for 1st parameter
     while locating ShapeRequest

这里的问题可能是什么?我相信我是在显式地指定类型为Shape的依赖项和注释AnnotatedRectangle必须注入类型为Rectangle的对象.

推荐答案

@AnnotatedRectangle批注放到构造函数的参数中,而不是放在字段中:

private final Shape shape;

@Inject
public ShapeRequest(@AnnotatedRectangle Shape shape) {
    System.out.println("Attempting injection");
    this.shape = shape;
}

如果使用构造器注入,注入的所有"元数据"都必须进入构造.Guicetry 构造函数注入或字段注入.不是两个都有.

另外,我会用@Qualifier取代@BindingAnnotation作为JSR标准.同样是根据Guice:

Guice的@BindingAnnotation在旧版本中也用于此目的 密码.

Java相关问答推荐

int Array Stream System. out. print方法在打印Java8时在末尾添加% sign

在现代操作系统/硬件上按块访问数据值得吗?

填写文本字段后锁定PDF

JPanel透支重叠的JComcoBox

如何正确创建序列图?

如何从错误通道回复网关,使其不会挂起

Spring Data JPA慢慢地创建了太多非活动会话

对于亚洲/香港,使用ResolverStyle.STRICT的LocalDate.parse返回意外结果

用OSQL创建索引

如何在JavaFX中处理多个按钮

Groovy/Java:匹配带引号的命令选项

在不使用instanceof或强制转换的情况下从父类变量调用子类方法

在Eclipse中可以使用外部字体吗?

在ECLIPSE上的M1 Pro上运行JavaFX的问题

按长度排序字符串数组

如果c不为null,Arrays.sort(T[]a,Comparator<;?super T>;c)是否会引发ClassCastException?

AspectJ编织外部依赖代码,重新打包jar并强制依赖用户使用它

双对象供应商

窗口启动后不久,从java.awt.Graphics disapear创建的矩形

在对象列表上调用提取后,如何判断没有值为空?