Guice 方法注入错误:“无法为 <class> 创建绑定。它已在一个或多个子注入器或私有模块上配置”

Roh*_*rni 5 java dependency-injection guice

我有以下课程,其中我需要使用 Guice 进行方法注入。

@Singleton
public class A {

    private final Injector injector;

    @Inject
    public A(Injector injector) {
       this.injector = injector;
    }

    public void method1() {
        ...
        final XInterface x = this.injector.getInstance(Key.get(XInterface.class, Names.named("provideX")));
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

该模块包含以下提供的方法:

public class MyModule extends AbstractModule {

    @Override void configure() {
        // no binding and scope for class A
    }

    @Provides
    @Named("provideX")
    public XInterface provide(@Named("isTest") boolean isTest, X x, XMock xMock) {
        return isTest ? xMock : x;
    }
}
Run Code Online (Sandbox Code Playgroud)

同一模块中isTest有一个提供者,在本次讨论中可以忽略。

现在,A 类中的注入给出了以下错误:

Unable to create binding for `A`. It was already configured on one or more child injectors or private modules. If it was in a PrivateModule, did you forget to expose the binding?
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪的其余部分并不是很有帮助。

在深入研究了一段时间并尝试了一些事情之后,我发现只需像这样定义SingletonA 类的范围:并删除A 类上的现有注释就可以解决该错误。现在我的问题有两个:MyModule.configure()bind(A.class).in(Singleton.class);@Singleton

  • 是什么导致了我第一次实现时的错误?
  • 在模块中定义单例作用域和使用单例作用域注释类之间有什么区别?为什么可以解决问题?

提前致谢!