0%

springBoot-Aop

文章字数:1063,阅读全文大约需要4分钟

依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import com.cenobitor.aop.annotation.Action;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;

@Aspect
@Component
public class LogAspect {

@Pointcut("@annotation(com.cenobitor.aop.annotation.Action)")
public void annotationPoinCut(){}

@After("annotationPoinCut()")
public void after(JoinPoint joinPoint){
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Action action = method.getAnnotation(Action.class);
}

@Before("execution(* com.cenobitor.aop.service.DemoMethodService.*(..))")
public void before(JoinPoint joinPoint){
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
}
}

注解说明

1
2
3
4
5
6
7
8
@Aspect 定义切面:切面由切点和增强(引介)组成(可以包含多个切点和多个增强),它既包括了横切逻辑的定义,也包括了连接点的定义,SpringAOP就是负责实施切面的框架,它将切面所定义的横切逻辑织入到切面所指定的链接点中。
@Pointcut 定义切点:切点是一组连接点的集合。AOP通过“切点”定位特定的连接点。通过数据库查询的概念来理解切点和连接点的关系再适合不过了:连接点相当于数据库中的记录,而切点相当于查询条件。
@Before :在目标方法被调用之前做增强处理,@Before只需要指定切入点表达式即可。
@AfterReturning : 在目标方法正常完成后做增强,@AfterReturning除了指定切入点表达式后,还可以指定一个返回值形参名returning,代表目标方法的返回值。
@Afterthrowing: 主要用来处理程序中未处理的异常,@AfterThrowing除了指定切入点表达式后,还可以指定一个throwing的返回值形参名,可以通过该形参名来访问目标方法中所抛出的异常对象。
@After: 在目标方法完成之后做增强,无论目标方法时候成功完成。@After可以指定一个切入点表达式。
@Around: 环绕通知,在目标方法完成前后做增强处理,环绕通知是最重要的通知类型,像事务,日志等都是环绕通知,注意编程中核心是一个ProceedingJoinPoint。
环绕通知需要ProceedingJoinPoint.proceed放行执行中间的代码

AspectJ表达式

用来解释aop连接点

  • 方法描述指示器
指示器 说明 使用
execution() 匹配方法执行的连接点 execution(方法修饰符 返回值方法名(参数) 抛出异常) 这个颜色表示不可省略部分所有部分都支持*全部匹配
  • 方法参数匹配
指示器 说明
args() 匹配当前执行的方法传入参数为指定类型
@args 匹配当前执行的方法传入的参数有指定注解的执行
  • 当前AOP代理对象类型匹配
指示器 说明
this() 用于匹配当前AOP代理对象类型的执行方法;注意是AOP代理对象的类型匹配,这样就可能包括引入接口也类型匹配
  • 目标类匹配
指示器 说明
target() 用于匹配当前目标对象类型的执行方法;注意是目标对象的类型匹配,这样就不包括引入接口也类型匹配
@target 用于匹配当前目标对象类型的执行方法,其中目标对象持有指定的注解
within() 用于匹配指定类型内的方法执行
@within 用于匹配所以持有指定注解类型内的方法
  • 标有此注解的方法匹配
指示器 说明
@annotation 用于匹配当前执行方法持有指定注解的方法
  • 匹配特定名称的Bean对象
指示器 说明
bean() Spring AOP扩展的,AspectJ没有对于指示符,用于匹配特定名称的Bean对象的执行方法
  • 引用其他命名切入点
指示器 说明
reference pointcut 表示引用其他命名切入点,只有@ApectJ风格支持,Schema风格不支持