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
提前致谢!
| 归档时间: |
|
| 查看次数: |
4294 次 |
| 最近记录: |