Spring
Pippo can be used together with the Spring framework, using Spring 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-spring contains SpringControllerFactory that it’s
a ControllerFactory
implementation that delegates to the Spring container to instantiate a given Controller
class. This allows for the instance to be configured via dependency injection (all Spring annotations are valid, AOP, …).
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-spring injects the ContactService service bean, so basically you don’t have to worry about any of that stuff.
To activate pippo-spring integration in your Application you must register SpringControllerFactory
and extend from ControllerApplication
instead:
public class MyApplication extends ControllerApplication {
@Override
protected void onInit() {
// create spring application context
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
// registering SpringControllerFactory
setControllerFactory(new SpringControllerFactory(applicationContext));
// add controller
GET("/", ContactsController.class, "index");
}
}
where SpringConfiguration
can looks like:
@Configuration
public class SpringConfiguration {
@Bean
public ContactService contactService() {
return new InMemoryContactService();
}
}
SpringControllerFactory
class has two constructors: with and without autoRegistering
. By default autoRegistering
is true. If autoRegistering
flag is set on true then if Spring
doesn’t contain a bean for a controller class, SpringControllerFactory
will create and register a BeanDefinition
.
If you want to modify the default bean definition of the Controller
you must override createBeanDefinition
method.
Also don’t forget to add pippo-spring as dependency in your project:
<dependency>
<groupId>ro.pippo</groupId>
<artifactId>pippo-spring</artifactId>
<version>${pippo.version}</version>
</dependency>
You can see a demo here