界面 -
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 不加载我的绑定?