2

界面 -

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

4

1 回答 1

2

这就是问题所在,我相信:

@Named('Mars') Add a = injector.getInstance(Add)

您只是要求一个实例Add- 您分配结果的变量具有@Named注释这一事实与 Guice 无关。我相信您需要使用具有正确名称绑定Injector.getInstance(Key)的正确类的键,例如

Add add = injector.getInstance(Key.get(Add, Names.named('Mars')))
于 2013-08-16T09:20:42.520 回答