我試圖爲我給出的庫創建一個外觀。在我的外觀中,我使用Guice來構造對象圖。對象圖中的深層是一個代理對象,它具有getURL/setURL方法。 在我的外觀中,如何獲取用於創建我的根對象的Proxy實例?我希望我的外觀具有URL getter和setter。在Guice對象圖中獲取對象
我想是這樣的:
public class SomeThingFacade() {
private final SomeThing thing;
private final HTTPProxy proxy;
public SomeThingFacade() {
MyModule module = new MyModule();
Injector injector = Guice.createInjector(module);
// this is the main class I'm making a facade for
this.thing = injector.getInstance(SomeThing.class);
// deep in the "thing" object graph is a Proxy implementation
this.proxy = injector.getInstance(HTTPProxy.class);
}
public void setURL(URL url) {
this.proxy.setURL(url);
}
}
但injector.getInstance創造了一個新的實例。
綁定在MyModule中:
bind(Proxy.class).to(HTTPProxy.class).asEagerSingleton();
我以前硬編碼在門面構造對象圖,但它與30個對象笨拙了。
基本上,我需要在創建後在對象圖中深入配置一個實例,但是我不確定如何獲取該實例。
基本上,我需要在創建後在對象圖中深入配置一個實例,但我不確定如何獲取該實例。 – kalithlev
我想我暗示你並沒有真正掌握它,除非它碰巧是一個單身人士。在注入之前,您必須在注入之前配置對象。在這種情況下,您的模塊應爲對象http://code.google.com/p/google-guice/wiki/ProvidesMethods或提供商http://code.google.com/p/google-吉斯/維基/ ProviderBindings。可能使用特定於實例的註釋http://code.google.com/p/google-guice/wiki/BindingAnnotations。因此,如果您的外觀需要新的代理配置,請爲此外觀定義特定的模塊。 – dlamblin