Concept of AOP (Aspect oriented programming) every spring programmer use without knowing about it .

Many of spring programmer these days, when it’s comes to AOP (Aspect oriented programming) says heard about it but never used it . It’s interesting to see that many of them use it without knowing about it . One of the example that most of us used is spring declarative transaction management annotation. We do know what @transactional annotation does but we do not know and doesn’t even care about how it is doing it ? Spring is using AOP here .

Let’s understand how AOP actually works . Well in theory when one bean(java object) call method of another bean then spring create a proxy between them . If there is an interface for that bean and coding is on that interface than it will work as proxy otherwise spring will create a proxy for it . This proxy can be programmed through AOP and we can code if we want to do something before method call,after method call,after exception throw etc .

Now let’s see how this theory works in actual . Let’s create one custom annotation like @transactional to understand it better .

Step 1 : To work AOP with spring we need to define

<aop:aspectj-autoproxy>

in custom-config.xml .

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        xmlns:context="http://www.springframework.org/schema/context"        xmlns:aop="http://www.springframework.org/schema/aop"        xmlns:mvc="http://www.springframework.org/schema/mvc"        xsi:schemaLocation="            http://www.springframework.org/schema/beans            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd            http://www.springframework.org/schema/context            http://www.springframework.org/schema/context/spring-context-3.1.xsd            http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

  <!-- Scans for application @Components to deploy -->
    <context:annotation-config/>
  <context:component-scan base-package="com.stevenlanders.*" />

  <!-- enable AOP -->
  <aop:aspectj-autoproxy/>

</beans>

Step 2 : Create you custom annotation .

@Retention(RetentionPolicy.RUNTIME)
public @interface LogDuration {
   String value();
}

Step 3 : Write your AOP class. To do it, You need to use @Aspect annotation on that class . Then you need to create advice in this class. To do so, You need to choose one of the annotation given below .
@Before – Run before the method execution
@After – Run after the method returned a result
@AfterReturning – Run after the method returned a result, intercept the returned result as well.
@AfterThrowing – Run after the method throws an exception
@Around – Run around the method execution, combine all three advices above.
We are going to choose @Around here as we need to start and stop timer before and after of this method execution .

@Aspect
public class AopExample{

    //for any method with @LogDuration, no matter what the return type, name, or arguments are, call this method
    @Around("execution(@com.stevenlanders.annotation.LogDuration * *(..)) && @annotation(logDurationAnnotation)")
    public Object logDuration(ProceedingJoinPoint joinPoint, LogDuration logDurationAnnotation) throws Throwable {

        //capture the start time
        long startTime = System.currentTimeMillis();

        //execute the method and get the result
        Object result = joinPoint.proceed();

        //capture the end time
        long endTime = System.currentTimeMillis();

        //calculate the duration and print results
        long duration = endTime - startTime;
        System.out.println(logDurationAnnotation.value()+": "+duration+"ms"); //you should use a logger  

        //return the result to the caller
        return result;
    }

}

Step 4 : Put your annotation on methods for which you want to print execution time .

@Controller
public class ExampleController{

     @RequestMapping("/api/example/hello")
     @LogDuration("Hello World API")
     public @ResponseBody String getHelloWorld(){
          try {
            Thread.sleep(3000);
          } catch (InterruptedException e) {
            throw new RuntimeException("Sleep Interrupted", e);
          }
          return "Hello World";
     } 

}

Step 5 : Run this code .

Hello World API: 3002ms

For more information, see the Spring AOP Documentation

Other related posts are :
Interview questions on concept of code on interface rather then class
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming
Top 10 spring interview questions and their answers. Spring basic concepts.
Logback logs are not working. Log4j logs are not working. Steps to make logging work.

Please share this posts on Facebook,Linkeedin,Google+,Twitter by clicking on below icons.

Advertisements