学习Spring AOP,代码如下:
@Component
@Aspect
public class FanAnnotationImpl {
@Pointcut("@annotation(com.fan.spboot.core.aopdemo.FanAnnotation)")
private void entry(){
System.out.println("entry annotation");
}
@Around("entry()")
public void around(ProceedingJoinPoint joinPoint)throws Throwable{
System.out.println("around before");
try {
joinPoint.proceed();
}catch (Exception e){
e.printStackTrace();
}
System.out.println("around after");
}
@Before("entry()")
public void before(){
System.out.println("Before entry");
}
@After("entry()")
public void after(){
System.out.println("After entry");
}
}
spring-aop-pointcut-tutorial 有介绍:
“方法声明称为切入点签名。它提供了一个名称,通知注释可以使用该名称来引用该切入点。”
让我感到困惑的是方法使用 @Pointcut ,它只是一个切入点签名?
因为我发现这个方法里的代码没有执行,改变这个方法的类型就可以了;
那为什么是方法呢?使用变量也可以吗?
你自己已经引用了手册。这很清楚,不是吗? Spring AOP 基于注解,而不是变量。注释是 Java 中向类、方法或其他语言元素添加信息的标准方法。
A @Pointcut
方法只是定义切入点的一种方法,可以在多个地方使用,例如如果你想组合多个切入点,例如pointcut1 && (pointcut2 || pointcut3)
或者只是在多个建议方法中使用相同的切入点。作为开发人员,这是一种不必重复自己并多次编写相同切入点的方法。另一个优点是您可以在一个地方修改切入点,并且它会在使用它的任何地方进行更新。
该方法注释为@Pointcut
当然,它永远不会被 Spring AOP 调用,因为该方法只是一个虚拟方法,您需要通过切入点注释进行装饰。毕竟,您需要将注释放在某个地方。
如果您仅在一个地方使用切入点,则无需通过以下方式定义它@Pointcut
,你可以直接将切入点写入你的@Before
, @After
or @Around
注解。
实际上这个答案几乎是多余的,因为 Spring AOP 手册中已经很好地解释了所有内容。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)