March 08, 2018

Aspect Oriented Programming..

Aspect-oriented programming or AOP is one of the feature provided by Spring, actually it's not just a feature it a model of programming itself.

Suppose we have a common procedure across different objects, e.g Log message. To implement this, we can have a logMessage() method in all the objects. But this is not really a good design, because we are repeating the same method in all the objects. What we can do, we will create a new Logger class, which has logMessage() method. All other objects will refer to the Logger object's logMessage() method to print the message.

Now, if you are making a design diagram which depicts the relationship between all the objects and you want to know which object is an important one (by checking their relationship with other objects). In such case, the Logger will be the most important object, although it's not adding any business value.

The problem with this approach is that there will be too many relationships to the crosscutting objects and we need to still write the code to call the logMessage() method in all the business objects. In case, we use a different log implementation, then we need to make changes in all the business objects and make the changes accordingly to call the new log method.

All the applications have one other cross cutting concerns like logging, security or transactions. With AOP, we can remove the cross cutting concerns.

With AOP, we will create a 'Logging Aspect' class. After creating the aspect, we do not reference it from the objects, instead we will define the 'aspect configuration' which tells to which objects or methods these aspects apply to.

Suppose we have three business objects Partner, Vendor and Customer, each having the create() method and we need a logging mechanism while creating the Vendor and Customer. We need to do 'aspect configuration', Spring will make sure to call the logging method before creating the Vendor or a Customer. In case you decide to change the logging mechanism, all you need to make changes in 'aspect configuration'.

We can configure aspect to run before or after a particular (target) method.

Steps we need to take to write Aspect oriented program:

  • Write Aspects.
  • Configure where the aspects apply.

No comments:

Post a Comment

RSSChomp Blog Directory