我正在使用Jersey-Guice配置一個Jersey應用程序,在此之後template。如果GuiceServletContextListener.getInjector()
方法返回的Injector
由Guice.createInjector()
創建,則一切正常。如果該注射器是另一個注射器的孩子,則綁定資源(例如下面代碼中的MyResource
)永遠不會被添加到澤西島ResourceConfig
,並且澤西公司因丟失根資源而投訴。我認爲綁定的資源不會被掃描,因爲通常的「INFO:將my.example.MyResource註冊爲根資源類」不會出現在日誌中。如果注射器是小孩,Jersey-Guice不處理綁定資源?
任何想法,爲什麼會發生這種情況?這兩個版本都顯示在下面。
另外一個問題:我試圖使用子注入器,因爲我想在我的Main()類中配置我的應用程序數據服務對象。澤西島的資源不僅僅需要訪問它。我仍然需要它注入澤西島的資源。
如果有更好的方式來共享應用程序注入器和servlet注入器之間的應用程序單例(比我當前使用的應用程序注入器的子servlet注入器更好),請告訴我。
此版本的作品。
public class MyConfig extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return Guice.createInjector(new ServletModule() {
@Override
protected void configureServlets() {
bind(MyResource.class);
serve("*").with(GuiceContainer.class);
}
});
}
}
雖然下面的代碼不起作用。
public class MyConfig extends GuiceServletContextListener {
final Injector parentInjector;
public MyConfig(Injector injector) {
this.parentInjector = injector;
}
@Override
protected Injector getInjector() {
return parentInjector.getChildInjector(new ServletModule() {
@Override
protected void configureServlets() {
bind(MyResource.class);
serve("*").with(GuiceContainer.class);
}
});
}
}