2011-02-25 68 views
0

運行我創建這樣的servlet吉斯:如何配置碼頭與吉斯和Vaadin

public class GuiceApplicationServlet extends AbstractApplicationServlet { 

    protected Provider<Application> applicationProvider; 

    public GuiceApplicationServlet() { 
     System.out.println("TTest"); 
    } 

    @Inject 
    public GuiceApplicationServlet(Provider<Application> applicationProvider) { 
     super(); 
     this.applicationProvider = applicationProvider; 
     System.out.println("Test"); 
    } 

    @Override 
    protected Class<? extends Application> getApplicationClass() 
      throws ClassNotFoundException { 
     return Application.class; 
    } 

    @Override 
    protected Application getNewApplication(HttpServletRequest request) 
      throws ServletException { 
     return applicationProvider.get(); 
    } 
} 

的web.xml:

<filter> 
     <filter-name>guiceFilter</filter-name> 
     <filter-class>com.google.inject.servlet.GuiceFilter</filter-class> 
    </filter> 

    <filter-mapping> 
     <filter-name>guiceFilter</filter-name> 
     <url-pattern>/*</url-pattern> 
    </filter-mapping> 

    <listener> 
     <listener-class>pl.koziolekweb.vaadin.guice.servlet.VaadinGuiceConfiguration</listener-class> 
    </listener> 


    <servlet> 
     <servlet-name>Vaadin Application Servlet</servlet-name> 
     <servlet-class>pl.koziolekweb.vaadin.guice.servlet.GuiceApplicationServlet</servlet-class> 
    </servlet> 

    <servlet-mapping> 
     <servlet-name>Vaadin Application Servlet</servlet-name> 
     <url-pattern>/*</url-pattern> 
    </servlet-mapping> 

的問題是,當我運行的碼頭,然後吉斯創建實例(在控制檯中打印「Test」),但是當我嘗試在瀏覽器中運行應用程序時,我得到了NPE,並在控制檯「TTest」中出現。

因此jetty創建另一個不受guice管理的servlet實例。

問題是如何將jetty配置爲僅使用guice?

回答

2

您必須創建一個延伸com.​google.​inject.​servlet.ServletModule(我們稱之爲FooModule)的guice servlet模塊。您可以通過重寫configureServlets()方法來定義您的綁定和通向servlet的路徑。

然後,您必須通過擴展com.google.inject.servlet.GuiceServletContextListener(我們稱之爲BarContextListener)來創建上下文偵聽器。在那裏,你必須實現getInjector()方法,用類似的東西:

protected Injector getInjector() { 
     Injector injector = Guice.createInjector(new FooModule()); 
     return injector; 
    } 

然後你從你的web.xml文件中刪除所有的servlet映射,然後把過濾器:

<filter> 
     <filter-name>guiceFilter</filter-name> 
     <filter-class>com.google.inject.servlet.GuiceFilter</filter-class> 
    </filter> 
    <filter-mapping> 
     <filter-name>guiceFilter</filter-name> 
     <url-pattern>/*</url-pattern> 
    </filter-mapping> 

和上下文偵聽您創建:

<listener> 
     <listener-class>path.to.package.of.context.listener.BarContextListener</listener-class> 
    </listener> 

由此全部您的servlets由Guice管理,並在應用程序的服務器端啓用依賴注入。它適用於Tomcat,所以它也適用於Jetty。不要忘記將guice-servlet-<version>.jar包含到你的類路徑中。我沒有和Vaadin一起使用它,但我想我的答案對你有一點幫助。

0

由於Guice應創建所有Servlet實例,因此必須從web.xml文件中刪除servletservlet-mapping條目。