Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aspectj @Around pointcut all methods in Java

Tags:

java

aop

i am writing a simple timer aspect to instrument all the methods in all the packages that belong my project. But, then the return types of various methods in those classes are different and I am getting this following error:

It only works for setter but not for getter...

Error: applying to joinpoint that doesn't return void

and here is my timeraspect...

@Around("execution(* com.myproject..*(..))")
public void log(ProceedingJoinPoint pjp) throws Throwable{


    LOG.info("TimerAspect");
    String name = pjp.getSignature().getName();
    Monitor mon = MonitorFactory.start(name);
    pjp.proceed();
    mon.stop();

    LOG.info("TimerAspect Mon" + mon);

    String printStr = mon.getLabel()+","+mon.getUnits()+","+mon.getLastValue()+","+mon.getHits()+","+mon.getAvg()+","+mon.getTotal()+","+mon.getMin()+","+mon.getMax()+","+mon.getFirstAccess()+","+mon.getLastAccess();

    File f = new File("target/stats.csv");
    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(f, true));
    bufferedWriter.write(printStr);
    bufferedWriter.newLine();
    bufferedWriter.flush();
    bufferedWriter.close();


}

Any clue to resolve this is greatly appreciated.

Thanks

like image 873
rb8680 Avatar asked Jun 30 '12 00:06

rb8680


People also ask

What is pointcut in AspectJ?

AspectJ provides primitive pointcuts that capture join points at these times. These pointcuts use the dynamic types of their objects to pick out join points. They may also be used to expose the objects used for discrimination. this(Type or Id) target(Type or Id)

What is pointcut in Java?

Pointcut is a set of one or more JoinPoint where an advice should be executed. You can specify Pointcuts using expressions or patterns as we will see in our AOP examples. In Spring, Pointcut helps to use specific JoinPoints to apply the advice.

What is the difference between JoinPoint and pointcut?

JoinPoint: Joinpoint are points in your program execution where flow of execution got changed like Exception catching, Calling other method. PointCut: PointCut are basically those Joinpoints where you can put your advice(or call aspect). So basically PointCuts are the subset of JoinPoints.

Which method is executed first in AOP?

Executing method on the target class Thus, Spring AOP injects a proxy instead of an actual instance of the target class. When we start the Spring or Spring Boot application, we see Spring executes the advice before the actual method.


1 Answers

You should capture the output from your adviced call and return that from your around advice along these lines:

@Around("execution(* com.myproject..*(..))")
public Object log(ProceedingJoinPoint pjp) throws Throwable{

....
Object result = pjp.proceed();
......
return result;
}

This will take care of all your calls

like image 122
Biju Kunjummen Avatar answered Sep 18 '22 12:09

Biju Kunjummen