文章目录
- 1、首先,引入相关jar包
- 2、面向切面原理,编写配置类横向扩展业务代码
- 方法执行周期所用注解
- 通过`@Pointcut`注解可以确定我们需要的切入点
- 常用api
1、首先,引入相关jar包
Maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.4.3</version>
</dependency>
Gradle
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-aop', version: '2.4.3'
2、面向切面原理,编写配置类横向扩展业务代码
- 我们需要在该类加上注解
@Aspect
和@Component
,表明该类为切面类,并且注入到Spring容器 - 在Springboot启动类添加注解
@EnableAspectJAutoProxy
,开始切面功能
如图
方法执行周期所用注解
我们可以通过注解来确定方法的执行周期。
-
@Before
方法执行之前 -
@After
方法执行之后 -
@AfterThrowing
抛出异常后执行 -
@AfterReturning
最后执行方法 -
@Around
环绕通知
现在我们需要确定在哪个业务方法增加日志。首先我们需要找到该方法
通过@Pointcut
注解可以确定我们需要的切入点
@Pointcut("execution( * com.mosukj.manage.controller.BuiPatientInfoController.add(..))")
public void patientAdd(){}
使用以上方法,该切入点可以多次引用。
引用方法。我们只需要@After("patientAdd()")
方法参数对象JoinPoint
:可以获取方法的所有参数以及等等一些方法的信息;
实例代码
@After("patientAdd()") //方法执行完之后执行,切入点为以上定义的方法patientAdd()
public void patientAdd(JoinPoint joinPoint){
Object[] args = joinPoint.getArgs();
HttpServletRequest request = (HttpServletRequest) args[0];
Long userId = getUserId(request);
Map param = (Map) args[2];
String patientName = param.get("buiPatientInfo_patientName").toString();
savelogs(userId, "添加了<"+patientName+">患者",51);
}
通过@Around
环绕通知注解可以处理所执行方法之前/之后/抛异常的时候,我们都可以编写自己所需要执行的日志请求
实例:
@Around("patientRecodedelete()")
public void handleExceptionLog(ProceedingJoinPoint jp) throws Throwable {
//此处可以编写方法执行之前的业务代码
try {
long a = System.currentTimeMillis();
// 通过切点,调用该方法,可打印日志,保存日志到数据库
Object proceed = jp.proceed(); //调用该方法
//方法执行之后的业务代码,可打印日志,保存日志到数据库
} catch (Throwable throwable) {
//方法执行失败的业务代码,可打印日志,保存日志到数据库
new RuntimeException("方法执行失败");
System.out.println("方法出现异常==》进行异常处理");
}
}
使用Springboot的Aop面向切面。我们就可以实时的记录方法执行之前,执行之后,抛出异常后的日志。
常用api
并且通过参数JoinPoint joinPoint
,可以获取该方法的基本属性。
joinPoint.getArgs(); //获取一个参数数组
joinPoint.getTarget(); //获取被代理的对象
joinPoint.getSignature().getDeclaringTypeName(); //获取所属类的类名
joinPoint.getSignature().getName(); //获取方法名
aop方式在使用环绕通知时:
参数ProceedingJoinPoint jp
。
可以使用
jp.proceed(); //调用被代理的方法