2012-05-09 77 views
1

讀取的類名稱的實例在我的項目中,我有一個配置文件,列出了接口的具體實現。Guice提供基於從文件

如何配置我的Guice模塊,以便在接口注入時可以從類型中獲取具體類的實例?

interface A{} 

class AImpl implements A{ @Inject public A(.....)} 

class B { 
    @Inject 
    public B(A a) {} 
} 


class MyModule extends AbstractModule { 
    ... 
    @Provides 
    public A getA(@ConfiguredClass String classname) { 
    Class<A> aClass = (Class<A>) Class.forName(classname); 
    // ??? 
    // this needs to be instantiated by Guice to fulfill AImpl's dependencies 
    return aClass.newInstance(); 
    } 
} 

config: 
class: my.package.AImpl 

回答

2

你可以在啓動過程中在配置文件中讀取,將其轉換爲Map<Class, Class>和飼料映射到模塊和配置所有像這樣的綁定:

public class MyModule extends AbstractMdoule{ 

    //interface -> concrete 
    Map<Class, Class> implementsMap; 
    ... 
    public void configure() { 
     for (Map.Entry<Class, Class> implEntry : implementsMap.entrySet()) { 
      bind(implEntry.getKey()).to(implEntry.getValue()); 
     } 
    } 
} 
+0

+1:而且還有一個相關的問題在http://stackoverflow.com/questions/765680/why-theres-no-configuration-file-at-all-for-dependency-injection-with-google-gu –