有一些项目需要记录特定页面的增删改查情况,所以需要利用切点来实现接口记录
导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- @Aspect需要的包 -->
<!-- https://mvnrepository.com/artifact/aopalliance/aopalliance -->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
先得了解切点的参数
- @Pointcut : 用来定义切点位置.可有多个,定制保存,添加等方法进行切入
@Pointcut(“execution(* com.demo.service...save*(…)) || execution(* com.demo.service...add*(…))”)
public void insertAndUpdateService() {
} - 环绕通知 @Around 在方法前后执行.可以用来修改方法参数,也可以用来修改方法返回值,或者阻止方法执行
@Around(value = “insertAndUpdateService()”)
public Object doBeforeAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
// 通过JoinPoint 获取通知的签名信息,如目标方法名,目标方法参数信息等,进行相关操作
} - @Before 方法前执行 可以获得方法的一些参数,获得方法开始执行时间
@Before(“insertAndUpdateService()”)
public void doBefore(JoinPoint joinPoint) {
} - @After 不论方法是否异常,都执行
@After(value = “@annotation(insertAndUpdateService)”)
public void after() {
} - @AfterReturning 方法正常下执行
@AfterReturning(value = “insertAndUpdateService()”, argNames = “joinPoint,rtv”, returning = “rtv”)
public void insertServiceCallCalls(JoinPoint joinPoint, Object rtv) throws Throwable {
} - @AfterThrowing 方法抛出异常后,记录异常
@AfterThrowing(pointcut = “insertAndUpdateService()”, throwing = “e”)
public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
}