CDI
Pippo can be used together with CDI, using Weld as the implementation mechanism.
When Pippo creates new instances of your various Controller
subclasses it delegates the instance creation to a ControllerFactory
.
The module pippo-weld contains WeldControllerFactory that it’s
a ControllerFactory
implementation that delegates to the Weld 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-weld injects the ContactService service bean, so basically you don’t have to worry about any of that stuff.
To activate pippo-weld integration in your Application you must register WeldControllerFactory
and extend from ControllerApplication
instead:
public class MyApplication extends ControllerApplication {
@Override
protected void onInit() {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
// registering WeldControllerFactory
setControllerFactory(new WeldControllerFactory(container));
// add controller
GET("/", ContactsController.class, "index");
}
}
For our demo project the ContactService bean was available in the parent maven module so a Producer was required. For this a utility class was necessary.
public class WeldBeanProducer {
@Produces
public ContactService contactService() {
return new InMemoryContactService();
}
}
Don’t forget to add pippo-weld as dependency in your project:
<dependency>
<groupId>ro.pippo</groupId>
<artifactId>pippo-weld</artifactId>
<version>${pippo.version}</version>
</dependency>
You can see a demo here