[英]Why do I have an error when I try to override a generic binding with Guice? (TypeLiteral)
I'd like to override a generic type binding, but I allways got the same " No implementation was bound
" error. 我想覆盖泛型类型绑定,但我总是得到相同的“
No implementation was bound
”错误。
I'm using roboguice 3. 我正在使用roboguice 3。
Here is a exemple of code that I use: 这是我使用的代码示例:
public interface IParser<I, O> {}
public class Parser1 implements IParser<String, String> {
IParser<String, String> mParser;
@Inject
public Parser1(IParser<String, String> parser) {
mParser = parser;
}
}
public class Parser2 extends Parser1 {
@Inject
public Parser2(IParser<String, String> parser) {
super(parser);
}
}
public class MyModule extends AbstractModule {
@Override
protected void configure() {
bind(new TypeLiteral<IParser<String, String>>() {}).to(new TypeLiteral<Parser1>() {});
}
}
And here is my injector creation : 这是我的注射器创建:
RoboGuice.getOrCreateBaseApplicationInjector(this,
RoboGuice.DEFAULT_STAGE,
RoboGuice.newDefaultRoboModule(this),
Modules.override(new MyModule()).with(new AbstractModule() {
@Override
protected void configure() {
bind(new TypeLiteral<IParser<String, String>>() {}).to(new TypeLiteral<Parser2>() {});
}
})
);
If I don't try to override it (only user Parser1), all is fine, when I override standard object with providers, it works well too, but not with TypeLiteral. 如果我不尝试覆盖它(只有用户Parser1),一切都很好,当我用提供者覆盖标准对象时,它也可以很好地工作,但不能用于TypeLiteral。
My error is : 我的错误是:
com.google.inject.CreationException: Unable to create injector, see the following errors:
1) No implementation for IParser<String, String> was bound.
What am I doing wrong? 我究竟做错了什么?
Thanks. 谢谢。
You should change definition of classes which are implemented your interface. 您应该更改实现接口的类的定义。
Try this: 尝试这个:
public class Parser1<I, O> implements IParser<I, O> {
}
public class Parser2<I, O> extends Parser1<I, O> {
}
And then you can bind your interface to class by this way: 然后,您可以通过以下方式将您的接口绑定到类:
bind(new TypeLiteral<IParser<String, String>>() {}).to(new TypeLiteral<Parser1<String, String>() {});
I'm not shure, but it looks remarkable to me that a binding to a conrete instance is used instead to a Class
: 我并不害羞,但对于我来说,使用conrete实例的绑定代替
Class
是非常值得注意的:
bind(new TypeLiteral>() {}).to( new TypeLiteral() {} ); bind(new TypeLiteral>(){})。to( new TypeLiteral(){} );
did you try 你试过了吗
bind(new TypeLiteral<IParser<String, String>>() {}).to(Parser2.class});
? ?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.