Fork me on GitHub

This page is valid in the context of Controllers.
Also, this page focuses on using Guice to inject dependencies in Pippo and not using Pippo as a dependency in an existing application. If you want to add Pippo (web layer) as dependency in an already existing Guice application, please see this text.

Pippo can be used together with the Guice, using Guice as a dependency injection container.
When Pippo creates new instances of your various Controller subclasses it delegates the instance creation to a ControllerFactory.
The module pippo-guice contains GuiceControllerFactory that it’s a ControllerFactory implementation that delegates to the Guice container to instantiate a given Controller class. This allows for the instance to be configured via dependency injection.

An example of such a Controller subclass could look as follows:

public class ContactsController extends Controller {

    @Inject
    private ContactService contactService;

    public void index() {
        List<Contact> contacts = contactService.getContacts()
        getResponse().bind("contacts", contacts).render("contacts");
    }

}

Pippo automatically creates the ContactsController instance and pippo-guice injects the ContactService service bean, so basically you don’t have to worry about any of that stuff.

To activate pippo-guice integration in your Application you must register GuiceControllerFactory and extend from ControllerApplication instead:

public class MyApplication extends ControllerApplication {

    @Override
    protected void onInit() {
        // create guice injector
        Injector injector = Guice.createInjector(new GuiceModule());

        // registering GuiceControllerFactory
        setControllerFactory(new GuiceControllerFactory(injector));

        // add controller
        GET("/", ContactsController.class, "index");        
    }

}

where GuiceModule might look like:

public class GuiceModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(ContactService.class).to(InMemoryContactService.class).asEagerSingleton();
    }

}

Also don’t forget to add pippo-guice as dependency in your project:

<dependency>
    <groupId>ro.pippo</groupId>
    <artifactId>pippo-guice</artifactId>
    <version>${pippo.version}</version>
</dependency>

You can see a demo here