前言
aop的理念是增强原有业务,对原业务无侵入;经常被使用于日志和事务处理。
一、pom引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
二、编写案例
1.目标类
package com.student.controller;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Create by zjg on 2023/5/1
*/
@RestController
public class SumController {
@RequestMapping("sum/{a}")
public String sum(@PathVariable Integer a,@RequestParam Integer b){
System.out.println("a+b="+(a+b));
JSONObject jsonObject=new JSONObject();
jsonObject.put("sum",a+b);
return jsonObject.toString();
}
}
2.切面类
package com.student.sys.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
* Create by zjg on 2023/5/1
*/
@Aspect
@Component
public class SumAop {
@Pointcut("execution(* sum(..))")
public void pointCut() {
System.out.println("Hello Aop! pointCut");
}
@Before("pointCut()")
public void before(JoinPoint joinPoint){
System.out.println("Hello Aop! before");
}
@After("pointCut()")
public void after(JoinPoint joinPoint){
System.out.println("Hello Aop! after");
//throw new RuntimeException("after过程出现异常!");
}
@Around("pointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
System.out.println("Hello Aop! around");
System.out.println("环绕查看目标类:"+point.getTarget().getClass());
System.out.println("环绕查看目标方法:"+point.getSignature());
System.out.println("环绕查看目标参数:"+point.getArgs());
return point.proceed();
}
@AfterThrowing(value="pointCut()", throwing="exception")
public void afterThrowing(Exception exception){
System.out.println("Hello Aop! afterThrowing");
System.out.println("exception:"+exception.getMessage());
}
}
3.输出
Hello Aop! around
环绕查看目标类:class com.student.controller.SumController
环绕查看目标方法:String com.student.controller.SumController.sum(Integer,Integer)
环绕查看目标参数:[Ljava.lang.Object;@68651ee8
Hello Aop! before
a+b=2
Hello Aop! after
总结
execution可以匹配包、类、方法、参数和返回值,搭配起来很灵活;
也可以根据注解匹配切面:@Around(“@annotation(org.aspectj.lang.annotation.Around)”)
参考文档
回到顶部