2011-10-04 27 views
0

我想基於直到運行時才知道的東西來改變注入的實現。具體來說,我希望我的應用能夠以不同的版本進行操作,其中「版本」在執行請求之前不會被確定。此外,「版本」可能會因請求而異。谷歌Guice和運行時不同的注入

閱讀文檔後,似乎我可以在需要根據「版本」選擇運行時實現的情況下實現提供程序。另外,我可以在果汁之上推出我自己的產品。

在這種情況下,實施提供商是最佳途徑嗎?我想知道是否有最佳做法,或者是否有其他人嘗試使用Guice來解決這個問題。

感謝您的幫助!

-Joe

+1

你是如何計劃實施的「版本」信息?方法參數?註釋? –

回答

0

我認爲,如果版本只能在運行時知道的,您必須提供版本的「服務」與自定義提供手動。也許是這樣的:

@Singleton 
public abstract class VersionedProvider<T, V> { 

    private Map<V, T> objects; 

    T get(V version) { 
     if (!objects.containsKey(version)) { 
      objects.put(version, generateVersioned(version)); 
     } 
     return objects.get(version); 
    } 

    // Here everything must be done manually or use some injected 
    // implementations 
    public abstract T generateVersioned(V version); 
} 
0
public class MyRuntimeServiceModule extends AbstractModule { 
    private final String runTimeOption; 

    public ServiceModule(String runTimeOption) { 
    this.runTimeOption = runTimeOption; 
    } 

    @Override protected void configure() { 

    Class<? extends Service> serviceType = option.equals("aServiceType") ? 
     AServiceImplementation.class : AnotherServiceImplementation.class; 
    bind(Service.class).to(serviceType); 
    } 
} 

    public static void main(String[] args) { 
    String option = args[0]; 
    Injector injector = Guice.createInjector(new MyRuntimeServiceModule(option)); 

}