Wednesday, January 23, 2008

Aspect Oriented Programming-Spring AOP

In continuation of the series of articles on Spring Framework,today lets explore the possibilities and solutions that can be achieved by using Aspect Oriented Programming,AOP and in particular Spring AOP.To start with I would like to delve upon core concepts related to AOP ,the myths and realities surrounding it,benefits over OOP(Object Oriented Programming) and the areas where it can be used effectively.

History of AOP?
object-oriented programming (OOP) introduced the concept of the object, which initiated a new way to structure applications and write programs. The same idea applies to the concept of the aspect.In 1996, Gregor Kiczales and his team at the Palo Alto Research Center (PARC), a subsidiary of Xerox Corporation that is located in California, originally defined the concept of the aspect.
Definition of aspect
An aspect is a common feature that's typically scattered across methods, classes, object hierarchies, or even entire object models. It is behavior that looks and smells like it should have structure, but you can't find a way to express this structure in code with traditional object-oriented techniques

AOP vs OOP
The aim behind the development of OOP was to organize the data of an
application and its associated processing into coherent entities. Doing so was achieved by having objects that encapsulate data along with the methods that manipulate the data and carry out the processing.From a conceptual point of view, an application is broken down according to the realworld objects that it models. In a stock-management application, for example, you might find
supplier, article, customer, and other types of objects.By grouping together all the objects that possess the same characteristics, the concept of a class complements the concept of the object.
OOP has undeniably improved software engineering.Developers have built more-complex programs in a simpler fashion than would have been possible through procedural programming. Furthermore, developers have written large applications in object-oriented languages. For example, the Java 2 Platform, Enterprise Edition (J2EE) application servers were programmed in the Java language. Similarly, developers have implemented complex class hierarchies to construct graphical user interfaces. The Swing API,included in Java 2 Platform, Standard Edition (J2SE), falls into this category.AOP simply adds new concepts that allow you to improve object-oriented applications by making them more modular. In addition, AOP streamlines the development process by allowing the separation of development tasks. For example, highly technical functionalities, such as security.AOP allows us to dynamically modify our static model to include the code required to fulfill the secondary requirements without having to modify the original static model

Benefits over OOP

Writing clear and elegant programs using only OOP is impossible in at least two cases when the application contains crosscutting functionalities, and when the application includes code scattering.Let us explore a bit on these limitations.

Cross-cutting concerns
While organizing an application into classes,the analysis must be driven by the need for separating and encapsulating the data and its associated processing into coherent entities.Although the classes are programmed independently of one another, they are sometimes behaviorally interdependent. Typically, this is the case when you implement rules of referential integrity. For example, a customer object must not be deleted while an outstanding order remains unpaid; otherwise, the program risks losing the contact details for that customer. To enforce this rule, you could modify the customer-deletion method so that it initially determines whether all the orders have been paid. However, this solution is deficient for several reasons:• Determining whether an order has been paid does not belong to customer management but to order management. Therefore, the customer class should not have to manage this
functionality. The customer class should not need to be aware of all the data-integrity rules that other classes in the application impose. Modifying the customer class to take these data-integrity rules into account restricts the possibilities of reusing the class in other situations. In other words, once the customer class implements any functionality that is linked to a different class, customer is no longer independently reusable, in many cases. Despite the fact that the customer class is not the ideal place to implement this referential-integrity rule, many object-oriented programs work this way for lack of a better solution. You might be thinking about integrating this functionality into an order class instead,but this solution is no better. No reason exists for the order class to allow the deletion of a customer. Strictly speaking, this rule is linked to neither the customers nor the orders but cuts across these two types of entities.One of the aims of dividing the data into classes is making the classes independent from one another. However, crosscutting functionalities, such as the rules of referential integrity,appear superimposed on the division—violating the independence of the classes. In other words, OOP does not allow you to neatly implement crosscutting functionalities.

Code-Scattering
In OOP, the principal way that objects interact is by invoking methods. In other words, an object that needs to carry out an action invokes a method that belongs to another object. (An object can also invoke one of its own methods.) OOP always entail two roles: that of the invoker and that of the invoked.When you write the code to call a method, you do not need to worry about how the service is implemented because the call interacts only with the interface of the invoked object. You need only ensure that the parameters in the call correspond to those of the method’s signature.Because methods are implemented within classes, you write each method as a block of code that is clearly delimited. To change a method, you obviously modify the file that contains the class where the method is defined. If you alter just the body of the method, the modification is transparent because the method will still be called in exactly the same way.However, if you change the method’s signature (for example, by adding a parameter),further implications arise. You must then modify all the calls to the method, hence you must modify any classes that invoke the method. If these calls exist in several places in the program,
making the changes can be extremely time-consuming.The main point is this: Even though the implementation of a method is located in a single class, the calls to that method can be scattered throughout the application. This phenomenon of code scattering slows down maintenance tasks and makes it difficult for object-oriented applications to adapt and evolve.

Ofcourse we can use design patterns like Observer & Decorator in OOP to handle such scenerios like cross-cutting concerns and code scattering.And the advantages associated by implementing them are enhanced modularity of the code and effective testing.In general Aspects are used to implement functionalities (security, persistence, logging, and so on) within an application.An aspect allows you to integrate crosscutting functionalities and code scattering into an object-oriented application by using the new concepts of the pointcut, the joinpoint, and the advice.

Pointcut
Its the point of execution in the application at which cross-cutting concern needs to be applied.
In aspect-oriented computer programming, a pointcut is a set of join points. Whenever the program execution reaches one of the join points described in the pointcut, a piece of code associated with the pointcut (called advice) is executed. This allows a programmer to describe where and when additional code should be executed in addition to an already defined behavior. This permits the addition of aspects to existing software, or the design of software with a clear separation of concerns, wherein the programmer weaves (merges) different aspects into a complete application. In Spring the a pointcut is just a set of methods that, when called, should have advices invoked around them. This is the second important pieces of a Spring AOP aspect implementation!

Join Points
A join point is a point in the control flow of a program. In aspect-oriented programming a set of join points is described as a pointcut. A join point is where the main program and the aspect meet(such as field access, method invocation , constructor invocation, etc.). Spring's built-in AOP only supports method invocation currently.

Advice
In aspect and functional programming, advice describes a class of functions which modify other functions when the latter are run; it is a certain function, method or procedure that is to be applied at a given join point of a program.

Here is the example ,The aspect ibelow parodies the traditional "Hello World" for AspectJ by providing an aspect that captures all calls to the void foo(int, String) method in the MyClass class.

A simple HelloWorld aspect in AspectJ

public aspect HelloWorld
{
pointcut callPointcut( ) :
call(void foo(int, String));
before( ) : callPointcut( )
{
System.out.println(
"Hello World");
System.out.println(
"In the advice attached to the call pointcut");
}
}

OK having understood the history behind AOP and the terminology associated with it,lets explore the subject for today,Spring AOP

AOP basics

  • Aspect: A modularized implementation of a software concern that cuts across various objects in a software implementation. Logging is a good example of an aspect. In Spring AOP, aspects are nothing more than regular Spring beans, which themselves are plain-old Java objects (POJO) registered suitably with the Spring Inversion of Control container. The core advantage in using Spring AOP is its ability to realize the aspect as a plain Java class.

  • Join point: A point during program execution, such as a method executing or an exception being handled. In Spring AOP, a join point exclusively pertains to method execution only, which could be viewed as a limitation of Spring AOP. However, in reality, it is enough to handle most common cases of implementing crosscutting concerns.

  • Advice: Information about "when" an aspect is to be executed with respect to the join point. Examples of types of advice are "around," "before," and "after." They specify when the aspect's code will execute with respect to a particular join point.

  • Pointcut: A declarative condition that identifies the join points for consideration during an execution run. Pointcut is specified as an expression. Spring AOP uses the AspectJ pointcut expression syntax. An example pointcut expression is: execution(* com.myorg.springaop.examples.MyService*.*(..)). Asterisks in the expression refer to wildcards, as is conventiona

Spring AOP

The Spring Framework integrates with more powerful AOP frameworks, such as AspectJ .To use Spring AOP, you need to implement cross-cutting concerns and configure those concerns
in your applications.Any advice written for Spring AOP is configurable in the Spring container through a simple, consistent configuration. This configuration is an important aspect of using AOP in Spring because it is the only one you need to remember for creating extension points to existing classes.For further understanding I recommend reading the following articles ,instead of me touching upon the Spring AOP concepts here again,as anyways they are self-explanatory.

Spring AOP

Implementing Spring AOP in Enterprise Applications

Implementing Cross Cutting concerns using Spring 2.0 AOP

Implementing Logging as an Aspect using Spring AOP Framework

Suggested Video Tutorial by Ramnivas Laddad on AOP(Author of AspectJ in Action)

GoogleTech Talks Video by Gregor Kiczales,who introduced Aspects



Print this post

0 comments: