Aspect Oriented Programming (AOP) and Spring

AOP is all about adding aspects to your code. So what are aspects? The code that we apply on Cross Cutting Concerns. Then what is Cross Cutting Concerns? Aspect, Jointpoint, Pointcut, Cross Cutting Concerns, Advice etc are the frequently used word in AOP world. AOP decomposes a system into concerns, instead of objects.

 

Aspect: It’s like a general feature you want to apply globally to your application like logging, exception handling, transaction management, performance management etc. It is also called Cross Cutting Concerns.

Advice: It is a piece of code/logic for implementing your advice.

Joinpoint: A single location in the program where an advice is applied like method invocation, constructor invocation etc.

Pointcut: A pointcut is set of Joinpoint where an advice is applied. In Spring set of method invocation is called Pointcut. There are different types of pointcut in spring like Regular Expression Pointcut, Attribute Driven Pointcut, and Dynamic Pointcut etc

Targets/Target Objects: The objects you want to apply an aspect or set of aspects.

As per me advice is very similar to Decorator. You can implement an advice by implementing org.aopalliance.intercept.MethodIntercept interface of spring. The MethodInterceptor interface is actually a child of the org.aopalliance.intercept.Interceptor interface, which is a child of another interface org.aopalliance.aop.Advice. In spring we generally use method interceptor. That is designed for method-invocation style advice. The MethodIntercept is really simple

 

public interface MethodInterceptor extends Interceptor {

            Object invoke(MethodInvocation invocation) throws Throwable;

}

Basically, when you write an advice for intercepting a method, you have to implement one method - the invoke method, and you are given a MethodInvocation object to work with. The MethodInvocation object tells us a bunch of stuff about the method that we’re intercepting, and also gives a hook to tell the method to go ahead and run.

public class LoginInterceptor implements MethodInterceptor {

           public Object invoke(MethodInvocation methodInvocation) throws Throwable {

               Log logger = LogFactory.getLog(methodInvocation.getClass());

               long startTime = System.currentTimeMillis();

               try {

                               Object[] args = methodInvocation.getArguments();

                               if (logger.isDebugEnabled()) {

                                    logger.debug(”Beginning method: ” +

                                                             methodInvocation.getMethod().getDeclaringClass() + “::” +

                                                             methodInvocation.getMethod().getName());

                                   if (null != args) {

                                               logger.debug(” with arguments: ” + args.toString());

                                   } else {

                                              logger.debug(” with no arguments”);

                                   }

 

                                    logger.debug(System.getProperty(”line.separator”));

                               } else if (logger.isInfoEnabled()) {

                                        logger.info(”Beginning method: ” + methodInvocation.getMethod().getDeclaringClass()

                                              + “::” + methodInvocation.getMethod().getName());

                                      logger.info(System.getProperty(”line.separator”));

                               }

                                              Object retVal = methodInvocation.proceed();

                               return retVal;

                      } finally {

                               if (logger.isInfoEnabled()) {

                               logger.info(”Ending method: ” +  methodInvocation.getMethod().getDeclaringClass() + “::” +

                               methodInvocation.getMethod().getName());

                               logger.info(”Method invocation time: ” + (System.currentTimeMillis() - startTime) + ”

                               msecs.”);

                               logger.info(System.getProperty(”line.separator”));

                                   }

                    }

           }

}

XML configuration for above interceptor is given below:

 

<bean id=”studentServiceTarget” class=”com.example.StudentServiceImpl”/>

 

<bean id=”myLogger” class=”com.example.LoginInterceptor”/>

   

<bean id=”studentService”

    class=”org.springframework.aop.framework.ProxyFactoryBean”>

    <property name=”proxyInterfaces”><value>com.example.StudentService</value></property>

    <property name=”target”><ref local=”studentServiceTarget”/></property>

    <property name=”interceptorNames”>

        <list>

            <value>myAdvisorLogger</value>

         </list>

    </property>

</bean>

 

Spring has multiple alternatives to the basic MethodInterceptor , however, (which is referred to in the Spring documentation as an ‘around’ advice) so that if you want to do more specific things, you can with less complication - these extensions come in the form of Spring-specific extensions to the Advice interface (siblings to the MethodInterceptor interface), and they include:

·         org.springframework.aop.MethodBeforeAdvice - Implementations of this interface have to implement this before method:

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

·         org.springframework.aop.AfterReturningAdvice - This interface’s method will be called on the return from the invocation of a method. Implementation of this interface have to implement this afterReturning method:

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

·         org.springframework.aop.ThrowsAdvice – Implementation of this interface havt to implement this afterThrowing method:

            void afterThrowing([Method], [args], [target], [some type of throwable] subclass)

 Below are hierarchy of Advice class:

 

In above article I have given only basic information about AOP. 

 

Reference Material:

·         http://static.springframework.org/spring/docs/1.2.x/reference/aop.html.

·        Spring in Action by Craig Walls, Ryan Breidenbach: this is the best book I have read on Spring (and yes I read this entire book).

Leave a comment

Your comment