我在ShoppingCart.java
中的public int quantity()
方法的切入点不起作用。我试图创建一个切入点来捕获public int quantity()
方法的返回值,但是@AfterReturning
切入点的相关建议似乎没有被调用,即使在主方法调用了quantity方法之后(参见文件AuthenticationAspect.java
,它试图定义一个afterReturning切入点)。
文件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();
}
}
1条答案
按热度按时间ni65a41a1#
returning
子句将匹配限制为仅返回指定类型值的那些方法执行。ShoppingCart.quantity()
方法返回int
,因此它与通知中声明的String
返回类型不匹配。您可以将retVal
类型更改为int
或Object
,它与任何返回值匹配。供参考:退货通知后