Spring Aspect Oriented Programming (AOP)

SHARE & COMMENT :

1) Introduction

One of the major features available in the Spring Distribution is the provision for separating the cross-cutting concerns in an Application through the means of Aspect Oriented Programming. Aspect Oriented Programming is sensibly new and it is not a replacement for Object Oriented Programming. In fact, AOP is another way of organizing your Program Structure. This first section of this article looks into the various terminologies that are commonly used in the AOP Environment. Then it moves into the support that is available in the Spring API for embedding Aspects into an Application . Finally the article concludes by giving a Sample Application.

also read:

2) Introduction to AOP

2.1) The Real Problem

Since AOP is relatively new, this section devotes time in explaining the need for Aspect Oriented Programming and the various terminologies that are used within. Let us look into the traditional model of before explaining the various concepts.
Consider the following sample application,
Account.java

public class Account{

    public long deposit(long depositAmount){

        newAmount = existingAccount + depositAccount;
        currentAmount = newAmount;
        return currentAmount;

    }

    public long withdraw(long withdrawalAmount){

        if (withdrawalAmount

The above code models a simple Account Object that provides services for deposit and withdrawal operation in the form of Account.deposit() and Account.withdraw() methods. Suppose say we want to add some bit of the security to the Account class, telling that only users with BankAdmin privilege is allowed to do the operations. With this new requirement being added, let us see the modified class structure below.
Account.java

public class Account{

    public long deposit(long depositAmount){

        User user = getContext().getUser();
        if (user.getRole().equals("BankAdmin"){
            newAmount = existingAccount + depositAccount;
            currentAmount = newAmount;
        }
        return currentAmount;

    }

    public long withdraw(long withdrawalAmount){

        User user = getContext().getUser();
        if (user.getRole().equals("BankAdmin"){
            if (withdrawalAmount

Assume that getContext().getUser() someway gives the current User object who is invoking the operation. See the modified code mandates the use of adding additional if condition before performing the requested operation. Assume that another requirement for the above Account class is to provide some kind of Logging and Transaction Management Facility. Now the code expands as follows,
Account.java

public class Account{

    public long deposit(long depositAmount){

        logger.info("Start of deposit method");
        Transaction trasaction  = getContext().getTransaction();
        transaction.begin();
        try{
            User user = getContext().getUser();
            if (user.getRole().equals("BankAdmin"){
                newAmount = existingAccount + depositAccount;
                currentAmount = newAmount;
            }
            transaction.commit();
        }catch(Exception exception){
            transaction.rollback();
        }
        logger.info("End of deposit method");
        return currentAmount;

    }

    public long withdraw(long withdrawalAmount){

        logger.info("Start of withdraw method");
        Transaction trasaction = getContext().getTransaction();
        transaction.begin();
        try{
            User user = getContext().getUser();
            if (user.getRole().equals("BankAdmin"){
                if (withdrawalAmount

The above code has so many dis-advantages. The very first thing is that as soon as new requirements are coming it is forcing the methods and the logic to change a lot which is against the Software Design. Remember every piece of newly added code has to undergo the Software Development Lifecycle of Development, Testing, Bug Fixing, Development, Testing, …. This, certainly cannot be encouraged in particularly big projects where a single line of code may have multiple dependencies between other Components or other Modules in the Project.

2.2) The Solution through AOP

Let us re-visit the Class Structure and the Implementation to reveal the facts. The Account class provides services for depositing and withdrawing the amount. But when you look into the implementation of these services, you can find that apart from the normal business logic, it is doing so many other stuffs like Logging, User Checking and Transaction Management. See the pseudo-code below that explains this.

public void deposit(){

    // Transaction Management
    // Logging
    // Checking for the Privileged User
    // Actual Deposit Logic comes here

}

public void withdraw(){

    // Transaction Management
    // Logging
    // Checking for the Privileged User
    // Actual Withdraw Logic comes here

}

From the above pseudo-code, it is clear that Logging, Transaction Management and User Checking which are never part of the Deposit or the Service functionality are made to embed in the implementation for completeness. Specifically, AOP calls this kind of logic that cross-cuts or overlaps the existing business logic as Concerns or Cross-Cutting Concerns. The main idea of AOP is to isolate the cross-cutting concerns from the application code thereby modularizing them as a different entity. It doesn’t mean that because the cross-cutting code has been externalized from the actual implementation, the implementation now doesn’t get the required add-on functionalities. There are ways to specify some kind of relation between the original business code and the Concerns through some techniques which we will see in the subsequent sections.

3) AOP Terminologies

It is hard to get used with the AOP terminologies at first but a thorough reading of the following section along with the illustrated samples will make it easy. Let us look into the majorly used AOP jargons.

3.1) Aspects

An Aspect is a functionality or a feature that cross-cuts over objects. The addition of the functionality makes the code to Unit Test difficult because of its dependencies and the availability of the various components it is referring. For example, in the below example, Logging and Transaction Management are the aspects.

public void businessOperation(BusinessData data){

    // Logging
    logger.info("Business Method Called");

    // Transaction Management Begin
    transaction.begin();

    // Do the original business operation here

    transaction.end();
}

3.2) JoinPoint

Join Points defines the various Execution Points where an Aspect can be applied. For example, consider the following piece of code,

public void someBusinessOperation(BusinessData data){

    //Method Start -> Possible aspect code here like logging.

    try{
        // Original Business Logic here.
    }catch(Exception exception){
        // Exception -> Aspect code here when some exception is raised.
    }finally{
        // Finally -> Even possible to have aspect code at this point too.
    }

    // Method End -> Aspect code here in the end of a method.
}

In the above code, we can see that it is possible to determine the various points in the execution of the program like Start of the Method, End of the Method, the Exception Block, the Finally Block where a particular piece of Aspect can be made to execute. Such Possible Execution Points in the Application code for embedding Aspects are called Join Points. It is not necessary that an Aspect should be applied to all the possible Join Points.

3.3) Pointcut

As mentioned earlier, Join Points refer to the Logical Points wherein a particular Aspect or a Set of Aspects can be applied. A Pointcut or a Pointcut Definition will exactly tell on which Join Points the Aspects will be applied. To make the understanding of this term clearer, consider the following piece of code,

aspect LoggingAspect {}
aspect TransactionManagementAspect {}

Assume that the above two declarations declare something of type Aspect. Now consider the following piece of code,

public void someMethod(){

    //Method Start

    try{
        // Some Business Logic Code.
    }catch(Exception exception){
        // Exception handler Code
    }finally{
        // Finally Handler Code for cleaning resources.
    }

    // Method End
}

In the above sample code, the possible execution points, i.e. Join Points, are the start of the method, end of the method, exception block and the finally block. These are the possible points wherein any of the aspects, Logging Aspect or Transaction Management Aspect can be applied. Now consider the following Point Cut definition,

pointcut method_start_end_pointcut(){

    // This point cut applies the aspects, logging and transaction, before the
    // beginning and the end of the method.

}

pointcut catch_and_finally_pointcut(){

    // This point cut applies the aspects, logging and transaction, in the catch
    // block (whenever an exception raises) and the finally block.

}

As clearly defined, it is possible to define a Point Cut that binds the Aspect to a particular Join Point or some Set of Join Points.

3.4) Advice

Now that we are clear with the terms like Aspects, Point Cuts and Join Points, let us look into what actually Advice is. To put simple, Advice is the code that implements the Aspect. In general, an Aspect defines the functionality in a more abstract manner. But, it is this Advice that provides a Concrete code Implementation for the Aspect.
In the subsequent sections, we will cover the necessary API in the form of classes and interfaces for supporting the Aspect Oriented Programming in Spring.

4) Creating Advices in Spring

As mentioned previously, Advice refers to the actual implementation code for an Aspect. Other Aspect Oriented Programming Languages also provide support for Field Aspect, i.e. intercepting a field before its value gets affected. But Spring provides support only Method Aspect. The following are the different types of aspects available in Spring.

  • Before Advice
  • After Advice
  • Throws Advice
  • Around Advice

4.1) Before Advice

Before Advice is used to intercept before the method execution starts. In AOP, Before Advice is represented in the form of org.springframework.aop.BeforeAdvice. For example, a System should make security check on users before allowing them to accessing resources. In such a case, we can have a Before Advice that contains code which implements the User Authentication Logic.
Consider the following piece of Code,
Authentication.java

public class Authentication extends BeforeAdvice{

    public void before(Method method, Object[] args, Object target) throws Throwable{

        if (args[0] instanceof User){
            User user = (User)args[0];
            // Authenticate if he/she is the right user.
        }

    }

}

The above class extends BeforeAdvice, thereby telling that before() method will be called before the execution of the method call. Note that the java.lang.reflect.Method method object represents target method to be invoked, Object[] args refers to the various arguments that are passed on to the method and target refers to the object which is calling the method.
System.java

public class System{

    public void login(){
        // Apply Authentication Advice here.
    }

    public void logout(){
        // Apply Authentication Advice here too.
    }
}

Note that, till now we have not seen any code that will bind the Advice implementation to the actual calling method. We will see how to do that in the Samples section.

4.2) After Advice

After Advice will be useful if some logic has to be executed before Returning the Control within a method execution. This advice is represented by the interface org.springframework.aop.AfterReturningAdvice. For example, it is common in Application to Delete the Session Data and the various information pertaining to a user, after he has logged out from the Application. These are ideal candidates for After Advice.
CleanUpOperation.java

public class CleanUpOperation implements AfterReturningAdvice {

    public void afterReturning(Object returnValue, Method method, Object[] args,
    Object target) throws Throwable{
        // Clean up session and user information.
    }

}

Note that, afterReturning() will be method that will be called once the method returns normal execution. If some exception happens in the method execution the afterReturning() method will never be called.

4.3) Throws Advice

When some kind of exception happens during the execution of a method, then to handle the exception properly, Throws Advice can be used through the means of org.springframework.aop.ThrowsAdvice. Note that this interface is a marker interface meaning that it doesn’t have any method within it. The method signature inside the Throws Advice can take any of the following form,

public void afterThrowing(Exception ex)

public void afterThrowing(Method method, Object[] args, Object target,
Exception exception)

For example, in a File Copy program, if some kind of exception happens in the mid-way then the newly created target file has to be deleted as the partial content in the file doesn’t carry any sensible meaning. It can be easily achieved through the means of Throws Advice.
DeleteFile.java

public class DeleteFile implements ThrowsAdvice{

    public void afterThrowing(Method method, Object[] args, Object target,
    IOException exception){

        String targetFileName = (String)args[2];
        // Code to delete the target file.
    }

}

Note that the above method will be called when an Exception, that too of type IOException is thrown by the File Copy Program.

4.4) Around Advice

This Advice is very different from the other types of Advice that we have seen before, because of the fact that, this Advice provides finer control whether the target method has to be called or not. Considering the above advices, the return type of the method signature is always void meaning that, the Advice itself cannot change the return arguments of the method call. But Around Advice can even change the return type, thereby returning a brand new object of other type if needed.
Consider the following code,

pubic void relate(Object o1, Object o2){

    o1.establishRelation(o2);

}

Assume that we have a method that provides an Association link between two objects. But before that, we have to we want to ensure that the type of the Objects being passed must conform to a standard, by implementing some interfaces. We can have this arguments check in the Around Advice rather than having it in the actual method implementation. The Around Advice is represented by org.aopalliance.intercept.MethodInterceptor.
ValidateArguments.java

public class ValidateArguments implements MethodInterceptor {

    public Object invoke(MethodInvocation invocation) throws Throwable {

        Object arguments [] = invocation.getArguments()
        if ((arguments[0] instanceof Parent) && (arguments[1] instanceof Child) ){
            Object returnValue = invocation.proceed();
            return returnValue;
        }
        throw new Exception ("Arguments are of wrong type");

    }
}

In the above code, the validation happens over the arguments to check whether they implement the right interface. It is important to make a call to MethodInvocation.proceed(), if we are happy with the arguments validation, else the target method will never gets invoked.

5) Creating Point Cuts in Spring

Point Cuts define where exactly the Advices have to be applied in various Join Points. Generally they act as Filters for the application of various Advices into the real implementation. Spring defines two types of Point Cuts namely the Static and the Dynamic Point Cuts. The following section covers only about the Static Point Cuts as Dynamic Point Cuts are rarely used.

5.1) The Point Cut Interface

Point Cuts in Spring are represented by org.springframework.aop.Pointcut. Let us look into the various components of this interface. Looking at the interface definition will have something like the following,
Pointcut.java

public interface Pointcut{

    ClassFilter getClassFilter()
    MethodMatcher getMethodMatcher()

}

The getClassFilter() method returns a ClassFilter object which determines whether the classObject argument passed to the matches() method should be considered for giving Advices. Following is a typical implementation of the ClassFilter interface.
MyClassFilter.java

public class MyClassFilter implements ClassFilter{

    public boolean matches(Class classObject){

        String className = classObject.getName();
        // Check whether the class objects should be advised based on their name.
        if (shouldBeAdviced(className) ){
            return true;
        }
        return false;
    }
}

The next interface in consideration is the MethodMatcher which will filter whether various methods within the class should be given Advices. For example, consider the following code,
MyMethodMatcher.java

class MyMethodMatcher implements MethodMatcher{

    public boolean matches(Method m, Class targetClass){

        String methodName = m.getName();
        if (methodName.startsWith("get")){
            return true;
        }
        return false;
    }

    public boolean isRuntime(){
        return false;
    }

    public boolean matches(Method m, Class target, Object[] args);

        // This method wont be called in our case. So, just return false.
        return false;
    }
}

In the above code, we have 3 methods defined inside in MethodMatcher interface. The isRuntime() method should return true when we want to go for Dynamic Point cut Inclusion by depending on the values of the arguments, which usually happens at run-time. In our case, we can return false, which means that matches(Method method, Class target, Object[] args) wont be called. The implementation of the 2 argument matches() method essentially says that we want only the getter methods to be advised.
We have convenient concrete classes’ implementation the Point Cut classes which are used to give advices to methods statically. They are

  • NameMatchMethod Pointcut
  • Regular Expression Pointcut

5.2) NameMatchMethod Pointcut

Here the name of the methods that are too be given advices can me directly mentioned in the Configuration File. A '*' represents that all the methods in the class should be given Advice. For example consider the following class,
MyClass.java

public class MyClass{

    public void method1(){}

    public void method2(){}

    public void getMethod1()

    public void getMethod2()

}

Suppose we wish that only the methods getMethod1() and getMethod2() should be given Advice by some aspect. In that case, we can have the following Configuration file that achieves this,


        get*

The Expression get* tells that all method names starting with the method name get will be given Advices. If we want all the methods in the MyClass to be adviced, then the 'value' tag should be given '*' meaning all the methods in the Class.

5.3) Regular Expression Pointcut

This kind is used if you want to match the name of the methods in the Class based on Regular Expression. Spring distribution already comes with two supported flavors of Regular Expression namely Perl Regular Expression (represented by org.springframework.aop.support.Perl5RegexpMethodPointcut) and Jdk Regular Expression (represented by org.springframework.aop.support.JdkRegexpMethodPointcut).
Considering the following class,
MyClass.java

public class MyClass{

    public void method1(){}

    public void method11(){}

    public void method2(){}

    public void getMethod1()

    public void getMethod11()

    public void getMethod2()
}

The Expression 'm*1' matches method1() and method11(), 'getMethod.' matches only getMethod1() and getMethod2(). The Configuration File should be populated with the following information for gaining this kind of support.


        m*1

6) Sample Application

6.1) Introduction

Let is illustrate the various types of Advices (Before Advice, After Advice, Throws Advice and Around Advice) that we saw before in this sample Application. For this sample application let us define Adder Service which provides logic for adding two numbers. The various classes involved in Application along with the Advices in the subsequent sections.

6.2) Addder.java

This is the interface definition for the Add Service. The interface name is Adder and it has one single method called add() taking two arguments both of type int.
Adder.java

package net.javabeat.spring.aop.introduction.test;

public interface Adder {

    public int add(int a,int b);

}

6.3) AdderImpl.java

The implementation class for the Add Service. The logic is as simple as it returns the summation of the two numbers given as arguments. Note that, in the later section we will see how Advices get bound with this Implementation Class.
AdderImpl.java

package net.javabeat.spring.aop.introduction.test;

public class AdderImpl implements Adder {

    public int add(int a, int b){
        return a+b;
    }

}

6.4) Before Advice Implementation

This is the Before Advice for the Adder Implmentation class. This class implements the before() method in the MethodBeforeAdvice interface by simply outputting a message telling that this advice is called.
LogBeforeCallAdvice.java

package net.javabeat.spring.aop.introduction.test;

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;

public class LogBeforeCallAdvice implements MethodBeforeAdvice{

    public void before(Method method, Object[] args, Object target) {
        System.out.println("Before Calling the Method");
    }

}

6.5) After Advice Implementation

The After Method Call Advice implements the AfterReturningAdvice interface providing implementation for the afterReturning() method. Like the Before Advice implementation, this Advice also outputs a simple message to the console.
LogAfterReturningAdvice.java

package net.javabeat.spring.aop.introduction.test;

import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;

public class LogAfterReturningAdvice implements AfterReturningAdvice{

    public void afterReturning(Object returnValue, Method method, Object[] args,
    Object target) throws Throwable {

        System.out.println("After Normal Return from Method");
    }

}

6.6) Throws Advice Implementation

This Advice will be called when some kind of Exception is caught during the method invocation. We have added a simple logic to simlate the exception when the user inputs are 0 and 0.
LogAfterThrowsAdvice.java

package net.javabeat.spring.aop.introduction.test;

import java.lang.reflect.Method;
import org.springframework.aop.ThrowsAdvice;

public class LogAfterThrowsAdvice implements ThrowsAdvice{

    public void afterThrowing(Method method, Object[] args, Object target,
    Exception exception){

        System.out.println("Exception is thrown on method " + method.getName());
    }

}

6.7) Around Advice Implementation

This Advice takes the entire control during the Method Execution. It decides whether the add() method should be called or not based on the user inputs. Note that, only if the user inputs are not 0 and 0, then the add() method will be called through MethodInvocation.proceed().
LogAroundAdvice.java

package net.javabeat.spring.aop.introduction.test;

import org.aopalliance.intercept.*;

public class LogAroundAdvice implements MethodInterceptor{

    public Object invoke(MethodInvocation methodInvocation) throws Throwable {

        Object arguments[] = methodInvocation.getArguments();
        int number1 = ((Integer)arguments[0]).intValue();
        int number2 = ((Integer)arguments[1]).intValue();

        if (number1 == 0 && number2 == 0){
            throw new Exception("Dont know how to add 0 and 0!!!");
        }
        return methodInvocation.proceed();
    }
}

6.8) Configuration File

The Configuration File has 3 sections. One section is the Advice Bean Definition Section which is the definition set for all the 4 advices which we saw before. All the advices are given identifiers like 'beforeCall', 'afterCall', 'throwCall' and 'aroundCall'. Then contains the Bean Definition for the Add implementation class which is giving the identifier 'adderImpl'.
The next interesting section is how to bind these advices to the implementation code. For this, we have to depend on ProxyFactory Bean. This Bean is used to create Proxy objects for the Add Implementation class along with the Advice implementation. Note that the property 'proxyInterfaces' contains the Interface Name for which the proxy class has to ge generated. In our case, it is going to be the Adder interface. The 'interceptorNames' property takes a list of Advices to be applied to the dynamically generated proxy class. We have given all the 4 advices to this property. Finally the implementation class for the Adder service is given in the 'target' property.
aop-test.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<!-- Advices -->
<bean id = "beforeCall"
class = "net.javabeat.spring.aop.introduction.test.LogBeforeCallAdvice" />

<bean id = "afterCall"
class = "net.javabeat.spring.aop.introduction.test.LogAfterReturningAdvice" />

<bean id = "throwCall"
class = "net.javabeat.spring.aop.introduction.test.LogAfterThrowsAdvice" />

<bean id = "aroundCall"
class = "net.javabeat.spring.aop.introduction.test.LogAroundAdvice" />

<!-- Implementation Class -->
<bean id = "adderImpl"
class = "net.javabeat.spring.aop.introduction.test.AdderImpl" />

<!-- Proxy Implementation Class -->
<bean id = "adder"
class = "org.springframework.aop.framework.ProxyFactoryBean">

<property name = "proxyInterfaces">
<value>net.javabeat.spring.aop.introduction.test.Adder</value>
</property>

<property name = "interceptorNames">
<list>
<value>beforeCall</value>
<value>afterCall</value>
<value>throwCall</value>
<value>aroundCall</value>
</list>
</property>

<property name = "target">
<ref bean = "adderImpl"/>
</property>
</bean>

</beans>

6.9) Test Class

Following is the test class for the Adder Service. The code loads the Bean Definition File by depending on the BeanFactory class. Watch carefully in the output for the various Advices getting called. Also, we have made to activate the Simulated Exception by passing 0 and 0 as arguments to the add() method call thereby making use of the Throws Advice.
AdderTest.java

package net.javabeat.spring.aop.introduction.test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;

public class AdderTest {

    public static void main(String args[]){

        Resource resource = new FileSystemResource("./src/aop-test.xml");
        BeanFactory factory = new XmlBeanFactory(resource);
        Adder adder = (Adder)factory.getBean("adder");
        int result = adder.add(10,10);
        System.out.println("Result = " + result);

        result = adder.add(0,0);
        System.out.println("Result = " + result);
    }
}

also read:

7) Conclusion

This article provided information on how to use Spring AOP for programming the Aspects in an Application. It started with defining what Aspects are and what are problems in having the Aspects directly embedded into the Application and how to separate them using AOP. It then looked briefly into the various AOP Terminologies like Advice, Point Cut, Join Points etc. Then it moved on into the various support for creating Advices using Spring AOP. Also covered in brief are the Static Point Cuts like Name Method Match and Regular Expression Point Cuts. Finally the article concluded with a Sample Application that illustrates the usage of different Advices.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. Hforhirenpatel says:

    It was nice……

  2. sumant pandey says:

    excellent article

  3. good and comprehensive

  4. sanjay says:

    Good article. Concepts are explained in simple manner. Looking for the detailed configuration file(aop-test.xml) :)

  5. Subodh Sharma says:

    Excellent Content……….Good for the begineers…explained in a very nice way…

  6. Aannd Soni says:

    aop-test.xml would be like this :

    beforeCall
    afterCall
    throwCall
    aroundCall

  7. Meghna swapnil says:

    Excellent !! great explanation.. Even this http://www.compiletimeerror.com/2013/05/spring-aop-around-advice-example.html might help… Have a look…

  8. this is the best article i have ever read about Spring AOP.keep up your good work..

  9. Bachan Joseph says:

    It was nice……

Trackbacks

  1. [...] not familiar with the spring framework, please read our previous articles introduction to spring, spring aop and spring [...]

  2. [...] The final section of the article is about achieving transaction management through annotations and AOP. The readers of this article are assumed to have a basic understanding on core Spring Framework. If [...]

  3. [...] not familiar with Spring framework, please read our articles on Spring MVC, Spring Interceptor and Spring AOP. Please subscribe here to receive the future [...]

  4. [...] Spring Aspect Oriented Programming (AOP) [...]

  5. [...] Spring Aspect Oriented Programming (AOP) [...]

  6. [...] Spring Aspect Oriented Programming (AOP) [...]

  7. […] you are beginner for spring framework, please read our article on introduction to spring framework, spring aop, spring mvc and list of spring articles. Javabeat covers extensive articles on the spring […]

  8. […] focus on its core logic. Furthermore, a unit test wouldn’t necessarily deal with all retry cases. Aspect-oriented programming (AOP) Aspect-oriented programming is a programming paradigm that allows modularizing crosscutting […]

  9. […] Spring Aspect Oriented Programming (AOP) […]

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better