Skip to content

Commit f9d4696

Browse files
committed
add Guice section
1 parent 5a80cfe commit f9d4696

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

_posts/2015-05-27-guice.md

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
---
2+
layout: page
3+
title: "Guice"
4+
category: mod
5+
date: 2015-05-27 15:27:38
6+
order: 15
7+
---
8+
9+
Pippo can be used together with the [Guice](https://github.com/google/guice), using Guice as a dependency injection container.
10+
When Pippo creates new instances of your various `Controller` subclasses it delegates the instance creation to a `ControllerFactory`.
11+
The module [pippo-guice]({{ site.codeurl }}/pippo-guice) contains [GuiceControllerFactory]({{ site.codeurl }}/pippo-guice/src/main/java/ro/pippo/guice/GuiceControllerFactory.java) that it's
12+
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.
13+
14+
An example of such a Controller subclass could look as follows:
15+
16+
```java
17+
public class ContactsController extends Controller {
18+
19+
@Inject
20+
private ContactService contactService;
21+
22+
public void index() {
23+
List<Contact> contacts = contactService.getContacts()
24+
getResponse().bind("contacts", contacts).render("contacts");
25+
}
26+
27+
}
28+
```
29+
30+
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.
31+
32+
To activate pippo-guice integration in your Application you must add `GuiceControllerFactory`:
33+
34+
```java
35+
public class MyApplication extends Application {
36+
37+
@Override
38+
protected void onInit() {
39+
// create guice injector
40+
Injector injector = Guice.createInjector(new GuiceModule());
41+
42+
// registering GuiceControllerFactory
43+
setControllerFactory(new GuiceControllerFactory(injector));
44+
45+
// add controller
46+
GET("/", ContactsController.class, "index");
47+
}
48+
49+
}
50+
```
51+
52+
where `GuiceModule` can looks like:
53+
54+
```java
55+
public class GuiceModule extends AbstractModule {
56+
57+
@Override
58+
protected void configure() {
59+
bind(ContactService.class).to(InMemoryContactService.class).asEagerSingleton();
60+
}
61+
62+
}
63+
```
64+
65+
Also don't forget to add pippo-guice as dependency in your project:
66+
67+
```xml
68+
<dependency>
69+
<groupId>ro.pippo</groupId>
70+
<artifactId>pippo-guice</artifactId>
71+
<version>${pippo.version}</version>
72+
</dependency>
73+
```
74+
75+
You can see a demo [here]({{ site.demourl }}/pippo-demo-guice)
76+

0 commit comments

Comments
 (0)