Fork me on GitHub

Dependency Injection of a Plain Old Java Object (POJO) Tutorial

This tutorial demonstrates the dependency injection of a Plain Old Java Object (POJO).

The example used in this tutorial is the following simple application to render a message to screen. Part of the message is obtained from a dependency injected POJO.

DiPojoHttpServer screen shot.

Download Tutorial Source


The following is the content of the template.

		<p>Hello ${audience}</p>

With the template logic.

public class TemplateLogic {

	public Pojo getTemplateData(Pojo dependency) {
		return dependency;

WoOF (via its underlying OfficeFloor framework) injects dependencies into methods. By injecting dependencies into methods, WoOF makes development of applications simpler. This is because the application logic is written as loosely coupled methods rather than highly coupled objects.

The injected dependency (POJO) will provide the remaining text of the rendered content. The code of the injected POJO is as follows.

public class Pojo {

	public String getAudience() {
		return "World";

Dependency Injection

Objects for dependency injection are configured in the application.objects file contained at the root of the class path. Providing this file is optional, as it is anticipated that WoOF annotations will provide most POJO dependency configuration. However, it is supported to extend WoOF applications with additional dependencies as required. The file may also be named application.objects.xml for easier editing by XML editors.

The configuration of dependency injecting the POJO is as follows.


	<managed-object class="net.officefloor.tutorial.dipojohttpserver.Pojo" />


WoOF auto-wires dependency injection based on type. Auto-wiring dependencies based on type is adequate (and much easier) for the majority of applications. WoOF's underlying OfficeFloor framework does provide manual dependency configuration, however this is seldom used as WoOF allows qualifying dependencies for auto-wiring.

The configuration above instantiates the POJO via its default constructor. Should more complex construction be required, please see the tutorials on managed objects.

A type attribute can be added to auto-wire the POJO based on one of its super types (e.g. an interface).

Unit Test

The unit test ensures the correct rendered content is received.

	public void testRenderPage() throws Exception {

		// Start the server

		// Obtain the page
		HttpResponse response = this.client.execute(new HttpGet(
		assertEquals("Should be successful", 200, response.getStatusLine()

		// Ensure page contains correct rendered content
		String page = EntityUtils.toString(response.getEntity());
		assertTrue("Ensure correct page content", page.contains("Hello World"));


The next tutorial covers injecting managed objects.