Robert Robert - 1 year ago 59
Java Question

Simple Example with Guice Servlets

I don't know how to proceed with a simple guice example. After reading the documentation I've done the following:

  • setup the guiceFilter

  • created an injector and instantiated a new ServletModule in a
    and added the listener to web.xml

  • bound
    in configure servlets

After I've done that how do I use dependency injection? Let's say I have an index.jsp, IndexController.class (servlet), and two classes called Person and Order with Person depending on Order. How do I inject the Order dependency into the Person constructor via guice and after I do that I would need to return say a list of this person's orders back to the controller? I've used Ninject with ASP.NET MVC in the past and that was pretty simple, but I'm very confused on how to implement even the simplest DI example with Guice. Thanks.

Answer Source

To get started, here's an example that injects a service returning a list of names into an index controller. (No trickery in this example, everything is explicit.)

ListService interface defines simple service.

public interface ListService {
    List<String> names();

DummyListService provides trivial implementation.

public class DummyListService implements ListService {
    public List<String> names() {
        return Arrays.asList("Dave", "Jimmy", "Nick");

ListModule wires ListService to the dummy implementation.

public class ListModule extends AbstractModule {
    protected void configure() {

GuiceServletContextListener implementation maps a servlet to index, and creates a ListModule as above.

protected Injector getInjector() {
    return Guice.createInjector(
            new ServletModule() {
                @Override protected void configureServlets() {
            new ListModule());

IndexController puts the names into the request scope (manually) and forwards to a JSP page.

public class IndexController extends HttpServlet {

    @Inject ListService listService;

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("names", listService.names());
        req.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(req, resp);


JSP page dumps the names (fragment only).

<c:forEach items="${names}" var="name">