Home > other >  Why AfterReturning PointCut is not working?
Why AfterReturning PointCut is not working?

Time:11-18

My pointcut for method public int quantity() in ShoppingCart.java is not working. I am trying to create a pointcut to capture the return value of the method public int quantity() but the relevant advice for @AfterReturning pointcut doesn't seem to get invoked even after the quantity method is invoked by main method (See the file AuthenticationAspect.java which is trying to define an afterReturning Pointcut).

File ShoppingCart.java

package org.example;

import org.springframework.stereotype.Component;

@Component
public class ShoppingCart {

    public int quantity()
    {
        System.out.println("\n Quantity method called");
        return 2;
    }
}

AuthenticationAspect.java

package org.example;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class AuthenticationAspect {

    @Pointcut("execution(* org.example.ShoppingCart.quantity())")
    public void afterReturningPointCut()
    {
    }

    @AfterReturning(pointcut = "afterReturningPointCut()", returning = "retVal")
    public void afterReturning(String retVal)
    {
        System.out.println("The quantity used is "   retVal);
    }
}

Main.java

package org.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);

        ShoppingCart cart = context.getBean(ShoppingCart.class);

        cart.quantity();
    }
}

CodePudding user response:

A returning clause restricts matching to only those method executions that return a value of the specified type.

The ShoppingCart.quantity() method returns int, therefore it doesn't match the String return type declared in the advice. You can change the retVal type to int or to Object, which matches any return value.

For reference: After Returning Advice

  • Related