How to implement AOP Profiling in Grails application

25 / Sep / 2012 by Mohit Garg 2 comments

In one of my recent project, i want to profile method execution time. I have used Spring AOP to profile method execution time.

It’s very easy to implement AOP profiling in grails

1. Suppose we have below mentioned service class, we want to log execution time of method saveDataStudent,saveDataUpdated methods in service class. We need to write aspect for it.

package com.service

import com.test.Student
class StudentService {
    Student saveDataStudent(Student student) throws Exception{
        return student.save(flush: true,failOnError: true)
    }

    Student saveDataUpdated(Student student){
        return student.save(flush: true,failOnError: true)
    }
}

2. Use following aspect code for profiling.

package com.spring3.base.test

import org.aspectj.lang.JoinPoint
import org.aspectj.lang.ProceedingJoinPoint
import org.springframework.stereotype.Component
import org.springframework.util.StopWatch
import org.aspectj.lang.annotation.*

@Aspect
@Component
class LoggerInterceptor {

     @Around("execution(* saveData*(..))")
    public Object profileSaveMethod(ProceedingJoinPoint call) throws Throwable {
        StopWatch clock = new StopWatch("Profiling:::::" + call.signature + ":::::Args::::::" + call.args
        );
        try {
            clock.start(call.toShortString());
            return call.proceed();
        } finally {
            clock.stop();
            System.out.println(clock.prettyPrint());
        }
    }

}

@Around(“execution(* saveData*(..))”) : It represents that this advice will execute for those methods whose name is starting with saveData.

Hope this code will help you :)

To know more about AOP, you can take the reference from following links:

http://www.tothenew.com/blog/integrating-of-spring-aop-with-grails-application/
http://static.springsource.org/spring/docs/2.5.5/reference/aop.html

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. Sridhar

    Hey. I am able to run it. I was testing with Unit test case. I tried integration and worked. beans were not injected and I had to configure my util class as bean. Then I worked as expected.

    Thanks.

    Reply
  2. Sridhar

    Hi Mohit,

    Thanks for nice article. I am following this article to implement AOP in one of our project. I am not able to run it.

    I configured:
    1. resources.groovy
    2. A util class which is target class
    3. Interceptor class with same method which you have shown here.

    But, I don’t see it being executed. Should it be only in services? or we can use any util or groovy/src class to implement it?

    Reply

Leave a comment -