Mentawai Web Framework

Dependency Injection

Instead of creating hard dependencies inside your classes, you should use the DI pattern (Dependency Injection) to resolve the class dependencies automatically (auto-wiring). In any application, a class usually depends on other classes to do its job. A classic example would be a DAO (Data Access Object) which depends/needs a java.sql.Connection to access the database.

Mentawai offers a very robust, transparent and automatic support for DI through the org.mentawai.filter.DIFilter global filter. For the case described above, where we want to inject a Connection inside the classes that need it, all we have to do in the ApplicationManager is:

					
	filter(new DIFilter()); // filter global and unique for all dependencies!
	
	di("connection", Connection.class);
					

Everytime an object is requested from the action input, the DIFilter will check if it has a dependency of the type Connection.class and with the name "connection". If it does, the DIFilter will look inside the action input for this dependency through the key "connection" (notice the same name for source and target) and inject it automatically inside the object that depends on it, in a process that some people call auto-wiring.

It is also possible to specify a different name for the instance that will be obtained from the action input and that will be injected inside the object that depends on it. The example below demonstrates this:

			
	filter(new DIFilter()); // filter global and unique for all dependencies!
					
	di("connection", Connection.class).source("conn");
	
	// or
	
	di("connection", Connection.class, "conn");
										

The above code looks for a property with the name "connection" of type Connection.class and looks for an object in the action input with the key "conn". The injection will be done through a setter method (Ex: setConnection()) or straight into the public or private field (Ex: Connection connection).

The combination of the global filters org.mentawai.filter.IoCFilter with the org.mentawai.filter.DIFilter makes Mentawai a very robust IoC container that should solve efficiently the majority of your IoC and DI problems.

The MyBooks Demo Application is a good example of how to use DAO with IoC and DI.