Spring Aop中四个重要概念,切点,切面,连接点,通知
- 通知: 就是我们编写的希望Aop时执行的那个方法。我们通过Aop希望我们编写的方法在目标方法执行前执行,或者执行后执行。
- 切点:切点就是我们配置的满足我们条件的目标方法。比如我们规定:名字前面是select开头的才执行我们自定义的通知方法。那么这些select开头的方法就是切点。
- 连接点:连接点可以说是切点的全集。切点是连接点的子集。也可以理解为,连接点是我们没有定义那个select开头规则时,满足条件的全部的方法。
- 切面:切面是切点和通知的组合称谓,就是变相给组合起了个名字。
切面日常使用:
1. 常规使用类名定义切点
2. 使用自定义注解,定义使用注解的方法即为切点。
自定义注解:
package com.test.config;
@Target({ElementType.METHOD, ElementType.TYPE}) // 注释合法位置
@Retention(RetentionPolicy.RUNTIME) // 注释保留策略
public @interface MyAopCutPoint {
}
注解在切面中的调用
@Pointcut("execution(* com.test.service.StudentService.save*(..))")
private void stuSaveSomeThing() {
}//切入点签名
@Pointcut("annotation(com.test.config.MyAopCutPoint)")
private void myAopCutPoint() {
}//切入点签名
@After(value = "stuSaveSomeThing() && myAopCutPoint()", argNames = "joinPoint, myAopCutPoi")
public void methodAfter(JoinPoint joinPoint, MyAopCutPoint myAopCutPoi) throws Throwable {
//something
// myAopCutPoi 具有属性,可直接调用。
}
如何获取注解中的属性值
import org.aspectj.lang.ProceedingJoinPoint;
@Around("SpecAuthCondPointCut()")
public Object specAuthCond(ProceedingJoinPoint proceedingJoinPoint){
Signature signature = proceedingJoinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature; // 转换成 方法签名
SpecAuthCond specA = methodSignature.getMethod().getAnnotation(SpecAuthCond.class);//获取接口对象
String deptField = specA.deptField();//deptField为属性字段,返回注解属性的值;
}