Tuesday, December 09, 2014

A new definition of Dependency Injection

The concept of Dependency Injection (DI) exists for a while. It was defined by Martin Fowler from the larger concept of Inversion of control (see here). This concept was defined as a mean to "wire" components together. Buy what does the term "wire" mean precisely? I think it's time to give to this concept of DI, that is apply in a vast area of frameworks, a more formal definition.


So what is Dependency Injection? Well, DI is just a form of generic programming. Usually genericity is obtained by applying parametric polymorphism to classes at the language level to get special parameterized classes or class templates. Then these class templates can be specialized to obtain regular monomorphic classes.

In case of DI, Genericity is obtained using subtyping polymorphism when designing classes. Specialization is obtained by creating prototypes from these classes. The next sections will explain and give examples to this concept of genericity associated to DI.

Genericity using parameterized classes

Generic programming is usually implemented in languages (such like Java and C++) with parametric polymorphism. A class can be parameterized with one or more formal type (or value) parameters.

The following simple example shows how classes can be made generic using parametric polymorphism.

Class templates

The following pseudo code shows how to design generic classes using parametric polymorphism.
// class templating using parameterized polymorphism
// Template pseudo language

template <class BookingDAO, long MAX>
class BookingService {

    BookingDAO bookingDAO = BookingDAO.new

    long count

    void book(bookingDetails) {
        if(count++ < MAX) {
            // do something with bookingDAO

template <class BookingService>
class BookingController

    BookingService bookingService = BookingService.new

    public void confirm() {

class JPABookingDAO {   
// use JPA entity manager...

The code simply defines a generic class BookingService wich is parameterized with a BookingDAO type and a long value MAX. The class is also tagged with the singleton scope. A BookingController class template is also defined on the same basis.

Template specialization

The following code shows how class templates can be specialized with effective types and values.

//class template instanciations
class BookingService<JPABookingDAO, 100> {


class BookingController<BookingService> {


Object lifecycle

One word about how object lifecyle is handled in the above example. To manage object lifecycles, we can use annotation based AOP. Classes can be tagged with the scope singleton. Then the annotation will be used by the AOP singleton aspect to intercept any call to the class constructor and return the same instance each time.

Genericity using DI

Dependency injection is based on subtyping polymorphism and prototype wiring. The following model shows the same example as above but using DI instead.

Generic class design

Classes can be made generic using subtyping polymorphism. Classes must reference other classes through polymorphic references to interfaces (or abstract classes) in order to allow the substitution by subtypes later in the prototyping phase.

 * Spring version
 * subtyping polymorphism + prototyping 
interface BookingDAO {}

class JPABookingDAO implements BookingDAO {
 // JPA stuff ...

interface BookingService {
    void book(Map bookingDetails);

class BookingServiceImpl implements BookingService {

    long count;
    BookingDAO bookingDAO; 

    long max;   

    public void book(Map bookingDetails) {
        if(count++ < max) {
            // do something with bookingDAO

class BookingController {

    BookingService bookingService;

    public void confirm() {
        Map bookingDetails = new HashMap();
        // set details

Prototyping phase

The prototypes are created form the generic classes. During this phase, polymorphic references are resolved by the injection of a concrete subtype.

Te following code illustrates prototyping phase using the Grails BeanBuilder.

// prototyping
def bb = new BeanBuilder()
bb.beans {

    bookingService(BookingServiceImpl) {
        bookingDAO = ref('bookingDAO')
        max = 100

    bookingController(BookingController) {
        bookingService = ref('bookingService')      

What does injection mean?

Injection (or component wiring) simply means the substitution of generic formal parameters by the effective parameters during the specialization.

Why using DI?

We have seen that DI is semantically equivalent to parameterized classes. Parameterized class-based genericity and load-time weaving AOP is a perfect combinaison to manage components. So why using DI? Simply because genericity based on parametric polymorphism is often poorly implemented in languages. In Java for example, class parameterization with primary values (String or int for ex.) doesn't exist. Other points are the use of proxy-based AOP with is more adapted to prototype-based programming and object lifecycle management.

Wednesday, November 10, 2010

New Web DSL in SDM O.4

As you already probably know Simple Dynamic Modules has been released recently in 0.4 version. You can read the release note here. This release comes with a lot of bugfixes and some interesting enhancements. Let's overview one of them.

The Web DSL

To use use the SDM Web DSL to easily configure your webapp, you just have to require the 'org.sdm:http' module. The semantic of the requiring script will be extended to support the methods defined by the DSL.

The following example shows how to define a filter, a listener and a servlet.

require 'org.sdm:http'

web(path:'/oauthdemo', war:'eu/aclement/oauthdemo/webapp/resources/') {
 initParams contextConfigLocation:'classpath:eu/aclement/oauthdemo/webapp/application-context.xml'
 listener className:'org.springframework.web.context.ContextLoaderListener'
 filter name:'springSecurityFilterChain', className:'org.springframework.web.filter.DelegatingFilterProxy'
 servlet(name:'CXFServlet', className:'org.sdm.cxf.SdmCxfServlet', url:'/services/*') {
  bus = serviceRegistry.lookup('cxf')
The above code is straight forward. You can pass a closure to the servlet method that is responsible to initialize the created servlet.

What's next?

We could imagine a higher level DSL dedicated to a particular web framework, that would be responsible to automatically create the servlet, filters and listeners required by the application. For example, for the JSF framework we could have:

require 'org.sdm:jsf'


With the appropriates conventions, this would allow to simplify the configuration to the very minimum.

Monday, August 23, 2010

Extender pattern in SDM

This article introduces the Extender pattern and how it is implemented in the Simple Dynamic Modules framework.

Pattern principles

The Extender pattern is one of the most powerful pattern coming from the OSGI world. This pattern defines the concept of meta modules, that can extend the semantic of other modules

A meta module usually defines one or more abstractions within a wide range of possibilities from a simple key/value configuration model to a complete language or DSL. Modules can use the models or languages provided by these meta modules.

Pattern implementation in SDM

Simple Dynamic Modules (SDM) version 0.3, that has been released recently, contains an implementation of the Extender pattern. Combined with the powerful meta programming capabilities of Groovy, SDM becomes the perfect tool to package and use DSLs (just like the way RubyGems does). Let's discover how it works.

Extender meta modules

The extender module simply has to implement the onRequire method in its main script (ModuleMain), which is called whenever the module is required by another module.

For example, in the Camel meta module (a module provided by SDM, exposing the Apache Camel ESB DSL), we can see that the main script uses meta-programing to add the Camel mixin to the requiring object.

package org.sdm.camel

require group: 'org.apache.camel', module: 'camel-spring', revision: '2.2.0'
def onRequire(ctx) {
   ctx.requiringObject.metaClass.mixin (org.sdm.camel.dsl.CamelMixin) 

The Camel mixin

The Camel mixin simply exposes the Camel DSL as a mixin.

Extended modules

The extended module script simply requires the extender module using the require method. Because it has been automatically enhanced at runtime by the extender module, the script can use the Camel DSL.

package org.sdm.testapp

require group: 'org.sdm', module: 'camel', revision: SDM_VERSION
routes {
   errorHandler noErrorHandler()
   from('cxfrs://bean://rsServer') {
      process new DebugProcessor()
      to 'bean://helloService'


Armed with the Extender pattern and combined to the powerful meta programming capabilities of Groovy, SDM becomes the perfect tool to package and use DSLs the most efficient way.

SDM allows the JVM platform to compete with the best modular and dynamic platforms like Ruby and its famous RubyGems.

Saturday, July 10, 2010

Simple DM for Maven 0.2 released

Simple Dynamic Modules for Maven 0.2 is released.

Feature list

  • Maven dynamic modules 
  • Module lifecycle management (start, stop, restart) at runtime 
  • Runtime dependency management 
  • Runtime module versioning 
  • Service activation 
  • Application server 

Check it out here:
Simple Dynamic Modules for Maven

Thursday, March 25, 2010

CSS fluid & accessible layout

This article demonstrates how to design fluid and multi-channel (from mobile to desktop screens) applications layout with CSS that can display indifferently on a mobile device or a desktop screen. We will use different technics such as relative positioning and dimensioning, CSS media queries and retractable panels.


Take a look at this page to see a fluid layout demo. Try to resize the browser window horizontally to see how the layout reacts. The demo will work indifferently on your desktop computer or your iphone. Note: the demo will work on any good modern browser: firefox and webkit based browsers.

Fluid layout

A fluid layout means a layout that can be dynamically adapted to various screen dimensions. To get a fluid layout the following requirements needs to be met:

Relative positioning and dimensioning

Floating blocks

Floating positioning is a subcase of relative positioning.

Retractable panels

To display a page on small screens sometimes it is necessary to retract panels. For example a lateral menu can be made retractable based on the device screen size using CSS 3 media queries.

Monday, March 15, 2010

About MVC pattern in JSF

MVC Pattern

MVC is a design pattern to develop layered applications. It is very popular especially on Web environment. There are hundreds of web frameworks that implements refinements of the MVC pattern. Most of them are implemented on top of the command pattern to be adapted to the request/response paradigm.

Note: This article deals only with MVC frameworks implemented on the server side, so this is NOT about MVC in RIA frameworks such as Dojo or Flex.

Command pattern based MVC

Most of the existing frameworks found around the web are based on the command pattern. Among them there are Struts, Rails, Spring MVC, etc...

The Command

The command object is simply an operation of the MVC controller. It can be implemented in different variations in the frameworks:

  • As an explicit object like in Struts (Action)
  • As closure or method like in Rails

Command parameters

Command objects have parameters (or data).These data objects (DTO) can be validated and filled automatically with homonym attributes from the request.

Data binding

Usually, in command pattern based MVC frameworks, the binding relation is a surjection from the model to the view properties. The inverse is not defined.


The JSF MVC is different from the former version because it has real views that lived on the server and emit events that are listen by the controllers. The server side views are connected to the DOM (in case of DOM rendering) through a bridge (not to be confused with the portlet bridge).

The bridge

The bridge is bidirectional and serves two purposes.

Event listening

First, it bridges the gap between the HTTP request/response paradigm with the event model thats exists in JSF. When a user clicks on a DOM widget, the DOM event is propagated to the UIComponent counterpart on the server server side, converted into a JSF event emitted by the component.

View rendering

The bridge triggers (render response phase) the view rendering and updates the DOM accordingly.

Bijective binding

The JSF binding model is bijective. It means that the same binding metadata are used to bind the model to the view properties in the "render response" phase and to bind the view to the model properties in the "apply request values" phase.

Friday, February 19, 2010

JSF like validation plugin for Grails


JSF has a nice server side component model for defining the views. The UI components (or widgets) live on the server and are composed together to form a view.

JSF provides a powerful data binding (plus validation and conversion) feature between the view and the model properties. Furthermore, the binding is bijective (or bidirectional), which means that this works also between the model and the widgets properties.

Grails doesn't have an equivalent server side component model, but instead is based on the Command pattern whereas the web request plays the Command role. Grails provides a binding framework that can bind request parameters to model properties but has to be invoked explicitly from the controller. Grails also provides a set of widgets (implemented as taglibs) but they are involved only in the rendering of views. Widget properties are also bound to the model with the help of Groovy scriptlets. So in Grails there is no bijective binding function.

The purpose of the autobind Grails plugin is to provide to full bijective binding (with validation and conversion) mechanism in a JSF like manner.


The autobind plugin requires the use of the Spring Webflow plugin available by default in Grails to define the control logic.


Autobind plugin installation

First you need to install the autobind plugin. Download it here: Autobind Plugin

Plugin installation is easy. Follow the instructions here: Grails plugins

You can type the following command from your grails project home to install the autobind plugin in your project:

grails install-plugin /path/to/downloaded/plugin/grails-autobind-0.1.zip

The bind function

To bind a widget property to a model bean property you have to use the bind function. You can use the immediate attribute if you want to skip the validation.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

<html xmlns="http://www.w3.org/1999/xhtml">
  <meta name="generator" content=
  "HTML Tidy for Linux/x86 (vers 11 February 2007), see www.w3.org" />
  <meta http-equiv="Content-Type" content="text/html; charset=us-ascii" />
  <meta name="layout" content="main" />

  <title>Edit Book</title>

  <div class="nav">
    <span class="menuButton"><a class="home" href=
    "${createLinkTo(dir:'')}">Home</a></span> <span class="menuButton">Book List</span>
    <span class="menuButton">New Book</span>

  <div class="body">
    <h1>Edit Book</h1>

    <div class="message">

    <div class="errors"></div><input type="hidden" name="id" value="${book.id}" />
    <input type="hidden" name="version" value="${book.version}" />

    <div class="dialog">
          <tr class="prop">
            <td valign="top" class="name"><label for="author">Author:</label></td>

            <td valign="top" class=
            "value ${hasErrors(bean: book, field: 'author', 'errors')}"><input type=
            "text" id="author" name="author" value=
            "${bind(bean: book, field:'author')}" /></td>

          <tr class="prop">
            <td valign="top" class="name"><label for="title">Title:</label></td>

            <td valign="top" class=
            "value ${hasErrors(bean: book, field: 'title', 'errors')}"><input type="text"
            id="title" name="title" value="${bind(bean: book, field: 'title')}" /></td>

    <div class="buttons"></div>

The controller

The control logic has to be implemented using a web flow. The edition flow contains no explicit calls to binding or validation logic. The book object within the conversation is implicitly updated and validated without any explicit call to the binding framework.
class BookController {

 def beforeInterceptor = {
  println "Controller Interceptor Tracing action ${actionUri}"

 def index = { 
  redirect(action: list, params: params)
 // the delete, save and update actions only accept POST requests
 static allowedMethods = [delete: 'POST', save: 'POST', update: 'POST']  
 def editionFlow = {
  start {
   action {
    def book = Book.get(params.id) 
    [book: book]
   on('success').to 'show'
  show {
   on('edit').to 'edit'
  edit {      
   on('update') {     
   }.to 'end'  

   on('cancel').to 'end'
  end {
   redirect(controller:"book", action:"list")
 def list = {
  params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
  [books: Book.list(), total: Book.count()]
 def delete = {
  def bookInstance = Book.get( params.id )
  if(bookInstance) {
   try {
    flash.message = "Book ${params.id} deleted"
   catch(org.springframework.dao.DataIntegrityViolationException e) {
    flash.message = "Book ${params.id} could not be deleted"
  else {
   flash.message = "Book not found with id ${params.id}"
 def create = {
  def book = new Book()
  book.properties = params
  return [book: book]

No binding and validation code

As you can see there is no binding and validation logic in controller actions.

Under the hood

The bind function

The bind function of the BindingTagLib store the binding metadata in the flash (or flow) scope to be reused when the form is post back.

For example, the bind function binds the author property of the book bean to the value property of the HTML input control with id "author".

The BindingTagLib

class BindingTagLib {

 private getBindings() {
  def ctx = RequestContextHolder.getRequestContext()?.flowScope ?: flash
  if (!ctx.bindings)
   ctx.bindings = []

 private getImmediates() {
  def ctx = RequestContextHolder.getRequestContext()?.flowScope ?: flash
  if (!ctx.immediateActions)
   ctx.immediateActions = []

 def bind = { attrs, body ->
  def bindings = getBindings()  
  bindings << attrs  
  out << fieldValue(attrs, body)  

 def actionButton = { attrs, body ->
  boolean immediate = attrs['immediate']
        if (immediate) {
         def immediates = getImmediates()
         immediates << attrs['name']
  out << submitButton(attrs, body)

Autobinder object

The autobinder object is responsible of validating and binding request submitted values to the model bean properties. For that, it uses binding metadata collected by the bind function when rendering the view and stored in the flow (or flash) scope .

class Autobinder {

 private static LOG = LogFactory.getLog(Autobinder.class)

 def eventFactory = new EventFactorySupport()

 def exceptionHandler = new AutobindExecutionExceptionHandler()

 def autobind() {
  try {
   def ctx = RequestContextHolder.getRequestContext()
   def exeCtx = ctx.getFlowExecutionContext()
   def reqCtx = ctx.getRequestScope()
   def flowSession = exeCtx.activeSession
   def state = flowSession.state
   def params = ctx.requestParameters
   def scope = ctx?.flowScope   

   def handlers = exeCtx.definition.exceptionHandlerSet
   handlers.add exceptionHandler
   LOG.debug "calling autobind"
   def bindings = scope.bindings ?: []
   def immediates = scope.immediateActions ?: []
   //reset bindings
   scope.bindings = null
   scope.immediateActions = null
   def eventId = params.asMap().keySet().find { n -> n =~ /_eventId_/ }
   if(!eventId) { return }         

   def m = eventId =~ /_eventId_(.*)/
   def event = m[0][1]
   if (immediates.find { it == event }) {
      LOG.debug "skipping binding for immediate action: $event" 
   def beans = [] as Set
   bindings.each { binding ->
    def field = binding.field
    def bean = scope.attributes.values().find { v ->
       v == binding.bean
    assert bean
    def value = params[field]   
    bean."$field" = value
    LOG.debug "Assigning [$bean] $field : $value"
    beans << bean
   boolean error = false
   beans.each { 
    if(!it.validate()) {
     error = true     
   if(error) {
    checkForErrors(ctx, scope.asMap())
    throw new ValidationException("edition", "edit", "validation error");
  } catch(IllegalStateException e) {
   LOG.debug e
  LOG.debug 'autobind end'

 def checkForErrors(context, scope) {
  for(entry in scope) {
   try {
             if(entry.value instanceof GroovyObject) {
              LOG.debug "check errors for ${entry.value}"
                 def errors = entry.value.errors
                 if(errors?.hasErrors()) {
                     context.flashScope.put("${GrailsApplicationAttributes.ERRORS}_${entry.key}", errors )
         catch(MissingPropertyException) {
                 // ignore

Spring webflow listener

The autobind is triggered when the Spring Webflow is resuming.

class AutobindFlowExecutionListener extends FlowExecutionListenerAdapter {

 private static LOG = LogFactory.getLog(AutobindFlowExecutionListener.class)

 def autobinder = new Autobinder()

 void resuming(RequestContext context) {
  LOG.debug "AutobindFlowExecutionListener resuming"