这是我的密码:
// Groovy
interface MyMapper {
Buzz toBuzz(Fizz fizz);
}
class MyMapperImpl implements MyMapper {
@Named("SIMPLE_FOOBAR")
Foobar foobar;
MyMapperImpl(Foobar foobar) {
super();
this.foobar = foobar;
}
@Override
Buzz toBuzz(Fizz fizz) {
// ...etc.
}
}
class Whistlefeather {
MyMapper mapper;
Whistlefeather(MyMapper mapper) {
super();
this.mapper = mapper;
}
void doSomething(Fink fink) {
Fizz fizz = getSomehow(fink);
Buzz buzz = mapper.toBuzz(fizz);
// Do something with 'buzz'...
}
}
class ApplicationMain {
Whistlefeather whistlefeather;
@Inject
ApplicationMain(Whistlefeather whistlefeather) {
super();
this.whistlefeather = whistlefeather;
}
static void main(String[] args) {
Injector injector = Guice.createInjector(new ApplicationModule());
ApplicationMain appMain = injector.getInstance(ApplicationMain);
appMain.run();
}
void run() {
whistlefeather.doSomething(new Fink());
}
}这是我的Guice模块:
class ApplicationModule extends AbstractModule {
@Override
protected void configure() {
// I have to name the Foobars because in reality there will be
// *many* of them, each configured slightly different.
bind(Foobar.class).annotatedWith(Names.named("SIMPLE_FOOBAR"))
.toInstance(new Foobar(true, true, false, 103, "yee haw"));
bind(MyMapper.class).to(MyMapperImpl);
}
}我的例外是:
Could not find a suitable constructor in com.me.myapp.MyMapperImpl.
Classes must have either one (and only one) constructor annotated
with @Inject or a zero-argument constructor that is not private.我的理解是,如果我要通过@Inject方法直接调用构造函数,我只需要用Injector#getInstance(...)注释它们。因为我是用ApplicationMain (它包含对Whistlefeather的引用,其中包含对MyMapper的引用)来实现这一点的,所以我不认为我需要注释MyMapperImpl构造函数。
你知道我在哪里出问题了吗?
发布于 2015-09-18 22:28:41
为了让Guice创建任何对象,它必须知道要使用哪个构造函数。这在整个对象图中都是正确的。
考虑以下代码:
public interface Something { }public class SomethingImpl implements Something {
private final String data;
public SomethingImpl(String data) {
this.data = data;
}
public SomethingImpl(Integer data) {
this.data = data.toString();
}
}public class AnotherClass {
private final Something something;
@Inject
public AnotherClass(Something something) {
this.something = something;
}
}public class MyModule extends AbstractModule {
@Override
protected void configure() {
bind(Something.class).to(SomethingImpl.class);
bind(String.class).toInstance("Hello!");
bind(Integer.class).toInstance(50);
}
}在这个场景中,Guice如何知道在SomethingImpl中使用哪个构造函数?如果你是Guice的作者,你会怎么写?
显然,你不能回答,因为这是不可能的。必须有某种机制来告诉Guice使用哪个构造函数,不管它是否由Injector.getInstance()调用;这就是为什么您必须至少注释一个构造函数。如果指定了没有参数的构造函数,Guice将默认使用,但是如果没有,Guice不知道该做什么。
https://stackoverflow.com/questions/32659933
复制相似问题