I create guice servlet like this:
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>
The problem is that when I run jetty then Guice create instance of servlet (print “Test” in console) but when I try to run application in browser i get NPE and in console “TTest” appear.
So jetty create another instance of servlet that is not managed by guice.
Question is how to configure jetty to use only guice?
You have to create a guice servlet module which extends
com.google.inject.servlet.ServletModule(let’s call itFooModule). You define there your bindings and paths to servlets by overridingconfigureServlets()method.Then you must create context listener by extending
com.google.inject.servlet.GuiceServletContextListener(let’s call itBarContextListener). There you must implementgetInjector()method, with something like that:Then you remove all servlet mappings from your web.xml, and then put filter:
and context listener You created:
By this all Your servlets are managed by Guice and enable dependency injection in server side of Your application. It works for me in Tomcat so it should also work on Jetty. Don’t forget to include
guice-servlet-<version>.jarinto your classpath. I didn’t use it with Vaadin, but I guess my answer helped You little bit.