1:导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2:编写对应的切面类
2.1给切面类打上@Component @Aspect注解
2.2在类中编写具体的增强的通知方法类型(以下五种类型)
以环绕通知为例(@Around ),也算最常用的
@Component
@Aspect
public class CalAspect {
@Pointcut("execution(* com.example.calculator.service.impl.AddServiceImpl.*(..))")
public void pointcut(){}
// @Around("execution(* com.example.calculator.service.impl.AddServiceImpl.*(..))")
@Around("pointcut()")
public Object aroundLog(ProceedingJoinPoint joinPoint) throws Throwable {
String methodName = joinPoint.getSignature().getName();
//1传入请求参数
Object[] args = joinPoint.getArgs();
System.out.println("传入请求参数:"+args[0]+" "+args[1]);
//2开始执行compute方法
System.out.println("开始执行"+methodName+"方法");
Object result = joinPoint.proceed();
//3方法返回结果
System.out.println("方法返回结果:"+result);
//4方法执行完毕
System.out.println(methodName+"方法执行完毕");
return result;
}
}
2.3切点有两种写法(如下)
1.
@Pointcut("execution(* com.example.calculator.service.impl.AddServiceImpl.*(..))")
public void pointcut(){}
@Around("pointcut()")
---------------------------------------------------------------------------------------
2.@Around("execution(* com.example.calculator.service.impl.AddServiceImpl.*(..))")
3.其他几种通知类型示例:
@Component
@Aspect
public class UserServiceAspect {
@Before("execution(* com.example.aop.service.UserServiceImpl.*(..))")
public void before(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
System.out.println("开始执行" + methodName + "方法");
}
@AfterReturning(pointcut = "execution(*
com.example.aop.service.UserServiceImpl.*(..))", returning = "result")
public void afterReturning(JoinPoint joinPoint, Object result){
System.out.println("方法返回结果:" + result);
}
@After("execution(* com.example.aop.service.UserServiceImpl.*(..))")
public void after(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
System.out.println(methodName + "方法执行完毕");
}
// @Around 可以实现 @Before + @AfterReturning + @After 的效果
@Around("execution(* com.example.aop.service.UserServiceImpl.*(..))")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
String methodName = joinPoint.getSignature().getName();
System.out.println("开始执行" + methodName + "方法");
//执行方法
Object result = joinPoint.proceed();
System.out.println("方法返回结果:" + result);
System.out.println(methodName + "方法执行完毕");
return result;
}
}