界面 -
public interface Add {
public int add(int a, int b)
}
实施1 -
class MartianAdd implements Add
public int add(int a, int b) {
return -a+b;
}
}
实施2-
public class SimpleAdd implements Add {
public SimpleAdd() {}
public int add(int a, int b) {
return a + b
}
}
class Bindings extends AbstractModule {
protected void configure() {
bind(Add).annotatedWith(Names.named('Earth')).to(SimpleAdd)
bind(Add).annotatedWith(Names.named('Mars')).to(MartianAdd)
}
}
主要课程 -
class Test {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new Bindings())
@Named('Mars') Add a = injector.getInstance(Add)
print a.class
print a.add(5, 8)
}
}
例外 -
Exception in thread "main" com.google.inject.ConfigurationException: Guice configuration errors:
1) No implementation for in.ksharma.Add was bound.
while locating in.ksharma.Add
Guice为什么不加载我的绑定?
答案 0 :(得分:2)
这是问题,我相信:
@Named('Mars') Add a = injector.getInstance(Add)
您只是询问 Add
的实例 - 您分配结果的变量具有@Named
注释的事实与Guice无关。我相信你需要使用Injector.getInstance(Key)
和正确的类的密钥来使用正确的名称绑定,例如
Add add = injector.getInstance(Key.get(Add, Names.named('Mars')))