2013-08-16 59 views
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) 
} 
} 

Main類 -

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不加載我的綁定?

回答

2

這是問題,我相信:

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

您只差要求Add實例 - 一個事實,即變量你分配結果有@Named註釋無關對Guice。我相信您需要使用Injector.getInstance(Key)以及正確類別的密鑰,正確名稱綁定爲,例如,

Add add = injector.getInstance(Key.get(Add, Names.named('Mars')))