问题描述
学习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中将信息添加到类,方法或其他语言元素的一种标准方法。
@Pointcut
方法仅是一种定义切入点的方法,该切入点可在多个地方使用,例如如果您想组合多个pointcut1 && (pointcut2 || pointcut3)
之类的切入点,或者只是在多个建议方法中使用相同的切入点。作为开发人员,这是您不必重复自己并多次编写相同切入点的一种方式。另一个优点是,您可以在一个地方修改切入点,并且在任何使用它的地方都可以对其进行更新。
Spring AOP当然不会使用@Pointcut
注释的方法,因为该方法只是一个虚拟对象,您需要通过切入点注释进行修饰。毕竟,您需要将注释放在某个地方。
如果仅在单个位置使用切入点,则无需通过@Pointcut
定义切入点,只需将切入点直接写入@Before
,@After
或{ {1}}注释。
实际上,这个答案几乎是多余的,因为Spring AOP手册对所有内容都进行了很好的解释。