我正在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的对象.