在spring boot 3.0中引入aop的过程
如下所示:
1、首先确保已经添加了相关依赖
可以通过maven或gradle来管理项目的依赖。
对于使用maven构建的项目,需要将以下依赖添加到pom.xml文件中
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-aop</artifactid>
</dependency>2、创建切面类(aspect)
并定义切点(pointcut)、前置通知(before advice)等逻辑。
切面类应该被注解为@component,这样才能被自动扫描到。
在com.lingyi.mybatis.aop包下创建一个timecustomaspect.java的aop类,增强方法执行的行为。

package com.lingyi.mybatis.aop;
import org.aspectj.lang.proceedingjoinpoint;
import org.aspectj.lang.annotation.after;
import org.aspectj.lang.annotation.around;
import org.aspectj.lang.annotation.aspect;
import org.aspectj.lang.annotation.before;
import org.springframework.stereotype.component;
import java.util.arrays;
/**
* 自定义aop切面
*/
@aspect
@component
public class timecustomaspect {
@before("execution(* com.lingyi.mybatis.controller.*.*())") //包com.lingyi.mybatis.controller下的所有类和类中的方法都满足该aop的条件
public void beforeadvice(){
system.out.println("方法执行前.....");
}
@after("execution(* com.lingyi.mybatis.controller.*.*())")
public void afteradvice(){
system.out.println("方法执行后.......");
}
@around("execution(* com.lingyi.mybatis.controller.*.*())")
public object recordtimecustom(proceedingjoinpoint pjp) throws throwable{
long start = system.currenttimemillis();
object result = pjp.proceed();
long end = system.currenttimemillis();
string classname = pjp.gettarget().getclass().getname();
string method = pjp.getsignature().getname();
string args = arrays.tostring(pjp.getargs());
system.out.println("类:"+classname + ",方法:"+method +",参数:"+args +",执行耗时:"+ (end - start));
return result;
}
}
3、测试
登录swagger ui界面,访问controller层某个接口。下面已/person接口为例
http://127.0.0.1:8081/swagger-ui/index.html


经过测试,编写的aop切面编程程序生效,aop会根据切点表达式自动进行切面处理。
当符合条件的方法调用发生时,就会执行相应的通知逻辑。
4、精细化切入
为了更加精细化对指定方法进行切入,切面还可以针对某些注解进行切入,从而实现对指定方法进行增强。

在方法上添加@loggin注解

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论