This is a fairly simple use of Guice with Java Spark. Basically, you need to extend SparkFilter as follows to create a Guice injector.
public class SparkGuiceFilter extends SparkFilter { private Injector injector = null; @Override protected SparkApplication[] getApplications(final FilterConfig filterConfig) throws ServletException { final SparkApplication[] applications = super.getApplications(filterConfig); if (this.injector == null) { this.injector = Guice.createInjector(new MainModule()); } if (applications != null && applications.length != 0) { for (SparkApplication application : applications) { this.injector.injectMembers(application); } } return applications; } }
Then you need web.xml and you need to run the Spark application as a regular war application using Jetty or any other servlet container:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <filter> <filter-name>SparkGuiceFilter</filter-name> <filter-class>com.devng.spark.guice.SparkGuiceFilter</filter-class> <init-param> <param-name>applicationClass</param-name> <param-value>com.devng.spark.SparkApp</param-value> </init-param> </filter> <filter-mapping> <filter-name>SparkGuiceFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
However, there are some limitations to this approach. You cannot use request or session areas with Guice. If you don’t need it, then you should go, otherwise you need to integrate Guice Servlet extensions and add GuiceFilter to your web.xml , as described in the official Guice documentation . You also need to make sure that you are using the same instance of the injector in GuiceFilter and SparkGuiceFilter , which you need to define GuiceServletContextListener in your web.xml , as described here .
You can find a fully working example in my GitHub here https://github.com/devng/demo/tree/master/sparkjava-guice
Devng source share