0

Is it possible to interrupt invoking the actual method from within the aspect execution? For example:

public class CheckPermissionAspect {
  
  @Around("@annotation(CheckPermission)")
  public Object methodLogging( ProceedingJoinPoint joinPoint) throws Throwable {
  
    // before method execution
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    log.info("Enter ==> " + signature.getMethod().getName());
    
    if ( getPermission( principal.getName()) == false ) {

       // break the execution of actual method
       Object result = null; // ???
       log.info("Break ==> " + signature.getMethod().getName());
    } else {

       // invoke the actual method
       Object result = joinPoint.proceed();

       // after method execution
       log.debug("Result: " + result);
       log.info("Leave ==> " + signature.getMethod().getName());
    }


    
    return result;
  
  }
  
}

To set Object result = null; does not work. Thank you for any help.

jrg
  • 33
  • 4
  • remove `Object result = joinPoint.proceed();` , that should stop the execution – R.G Jul 19 '22 at 09:14
  • Do go through [Around Advice](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop-ataspectj-around-advice).- *Within the body of the advice method, you must invoke proceed() on the ProceedingJoinPoint in order for the underlying method to run* – R.G Jul 19 '22 at 09:20

1 Answers1

0

From Spring Reference documentation : Around Advice

Within the body of the advice method, you must invoke proceed() on the ProceedingJoinPoint in order for the underlying method to run

If joinPoint.proceed() is removed from the code or an exception is thrown before joinPoint.proceed() statement or a return is issued before joinPoint.proceed() statement , the execution of the underlying method would get interrupted.

Update : to answer the comment

Spring AOP is proxy based. To understand this concept better , do read through : Understanding AOP proxies

An advice is placed between the calling method and the target. All calls to the target method gets intercepted and advised.

You could throw an exception upon validation ( Do note that the exception type thrown should match the exception type of the target method . Go through this Q&A).

The exception/return value from the advise would reach back the calling method .

R.G
  • 6,436
  • 3
  • 19
  • 28
  • Thank you for the answer. And is it possible to handle the return value in the annotated method? For example: return "no permission for user xy"; in the AspectMethod. Where and how can I access the return value? – jrg Jul 19 '22 at 09:49
  • @jrg answer updated , please go through . If your question is answered , do mark this as answer and upvote if it helped. – R.G Jul 19 '22 at 10:23