Posts Tagged ‘AOP’

Using Spring For Dependency Management

Sunday, April 26th, 2009

Spring is often times considered a web application library similar to the EJB 3.x stack.  However, Spring is so much more and can live in standalone applications as well.  Today I am going to touch on using Spring in standalone applications to handle dependency or configuration management.  I do not mean configuration management in the sense of CMS, but in the sense of handling and creating inner-dependencies between business objects, especially in the aspect of singletons.  One of the biggest issues with applications is high coupling by having to have objects create other objects, assign the relationships, and manage those dependencies.  However, one of the primary goals of any application is loose coupling, which in turn reduces maintenance.  Some of the traditional ways of handling these types of scenarios include:

  • Factories that create the instances and setup the dependencies.  While this abstracts the configuration to a factory, it still requires high coupling in the factory to talk to other factories and know about the objects and their inner dependencies.  It also requires static classes for the factories typically, which reduces testability.  My general rule of thumb is to reduce static classes in order to improve pluggability and testability.
  • Custom XML configuration to setup the dependencies and objects.    This pattern abstracts away all the coupling, but requires yet another XML format to be defined, a custom parser to be written, etc.  This can be a tedious operation depending on how fine grained and customizable the format is.

Spring offers a much better approach to this.  It allows you to use either annotations or XML configuration to setup the dependencies.  The difference with Spring’s XML configuration is that it is highly dynamic and flexible and offers several capabilities.  Further, Spring offers other support including AOP in order to separate and handle cross cutting concerns.  For example, you can easily add security or logging around any method invocation without the associated class having to manage that relationship.  In the end, your objects only deal with the objects they must directly deal with resulting in very loose coupling and high testability.

(more…)