You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Guice依赖注入报错[Guice/MissingImplementation]:Shape无绑定实现排查

问题原因及解决方法

你的问题核心是Guice不知道要给构造函数的Shape参数注入哪个实例,具体问题点和修复步骤如下:

1. 构造函数参数缺少绑定注解

你在AppModule里绑定的是带@AnnotatedRectangle注解的Shape,但ShapeRequest的构造函数参数Shape shape没有标注这个注解,Guice会默认寻找无注解的Shape实现绑定,而你并没有定义这个绑定,所以触发报错。

2. 字段上的注解无效

你在private final Shape shape字段上加了@AnnotatedRectangle,但因为你用的是构造注入(@Inject标注构造函数),字段的注解不会被Guice处理,这个注解是多余的。

3. 自定义注解的Target范围不足

你的@AnnotatedRectangle注解的@Target只包含ElementType.FIELD,但需要在构造函数参数上使用它,所以要把ElementType.PARAMETER也加入Target范围。


修复后的代码

1. 修改ShapeRequest构造函数,给参数添加注解

@Singleton
public class ShapeRequest {

    private final Shape shape;

    @Inject
    public ShapeRequest(@AnnotatedRectangle Shape shape) { // 添加注解标记参数
        System.out.println("Attempting injection");
        this.shape = shape;
    }

    // 其余方法保持不变
}

2. 更新@AnnotatedRectangle的Target范围

@BindingAnnotation
@Target({ElementType.FIELD, ElementType.PARAMETER}) // 新增PARAMETER类型
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotatedRectangle {
}

3. 原AppModule绑定逻辑无需修改

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

修改完成后,Guice就能明确识别要给构造函数注入带@AnnotatedRectangle注解的Rectangle实例,报错问题即可解决。

内容的提问来源于stack exchange,提问作者halfwind22

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 17:27:42