导入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
定义注解
- InsertLog.java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface InsertLog {
String value() default "";
}
- UpdateLog.java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UpdateLog {
String value() default "";
}
- DeleteLog.java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DeleteLog {
String value() default "";
}
定义切面
- AnnocationPointcut.java
@Component
@Aspect
@Slf4j
public class AnnocationPointcut {
@Pointcut("@annotation(com.annocation.InsertLog)")
public void insertLogPointcut(){}
@Pointcut("@annotation(com.annocation.DeleteLog)")
public void deleteLogPointcut(){}
@Pointcut("@annotation(com.annocation.UpdateLog)")
public void updateLogPointcut(){}
@After("insertLogPointcut()")
public void logInsert(JoinPoint jp){
Object[] args = jp.getArgs();
log.info("新增数据:" + args[0].toString());
}
@After("deleteLogPointcut()")
public void logDelete(JoinPoint jp){
Object[] args = jp.getArgs();
log.info("删除数据:" + args[0].toString());
}
@After("updateLogPointcut()")
public void logUpdate(JoinPoint jp){
Object[] args = jp.getArgs();
log.info("更新数据:" + args[0].toString());
}
}
使用
例如插入日志。在插入方法上添加注解,会在插入结束后,把参数记录下来。
@Transactional(rollbackFor = Exception.class)
@Override
@InsertLog
public Result<List<InsReceiptResult>> insReceipt(InsReceiptParam param) {
...
}
扩展
1、PointCut的表达式标签
- execution:用于匹配方法执行的连接点
- within:用于匹配指定类型内的方法执行
- this:用于匹配当前AOP代理对象类型的执行方法;注意是AOP代理对象的类型匹配,这样就可能包括引入接口也* 类型匹配
- target:用于匹配当前目标对象类型的执行方法;注意是目标对象的类型匹配,这样就不包括引入接口也类型匹配
- args:用于匹配当前执行的方法传入的参数为指定类型的执行方法
- @within:用于匹配所以持有指定注解类型内的方法
- @target:用于匹配当前目标对象类型的执行方法,其中目标对象持有指定的注解
- @args:用于匹配当前执行的方法传入的参数持有指定注解的执行
- @annotation:用于匹配当前执行方法持有指定注解的方法
- bean:Spring AOP扩展的,AspectJ没有对于指示符,用于匹配特定名称的Bean对象的执行方法
10种标签组成了12种用法,关于具体的用法,可以参考@Pointcut 的 12 种用法,你知道几种?
2、JoinPoint和ProceedingJoinPoint
-
JoinPoint:在除了@Around以外使用。(@Befor、@After、@AfterReturning、@AfterThrowing)
-
ProceedingJoinPoint:在@Around中使用
作用
- Object[] getArgs:返回目标方法的参数
- Signature getSignature:返回目标方法的签名
- Object getTarget:返回被织入增强处理的目标对象
- Object getThis:返回AOP框架为目标对象生成的代理对象
- … …