一、AOP 概念
面向切面编程,通过预编译方式和运行期动态代理实现程序功能统一维护的一种技术。
二、编码
2.1 添加 maven 依赖
<!-- spring boot支持aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.2 编写 aop 切面类
/*
@Aspect:表明这是一个切面类
@Pointcut:切入点,后面的execution是用于使用切面的连接点
@Before:在方法前执行
@After:在方法后执行
@AfterReturning:在方法执行后返回一个结果后执行
@AfterThrowing:在方法执行过程中抛出异常后的时候执行
@Around:环绕通知,可以在执行前后都使用,这个方法的参数必须为ProceedingJoinPoint,proceed()方法就是被切面的方法,
上面四个方法可以使用JoinPoint,JoinPoint包含了类名,被切面的方法,参数等信息。
*/
@Aspect
@Component
public class TestAspectUtil {
@Pointcut("execution(public * com.aop.*.*(..))")
public void TestAspect(){
}
@Before("TestAspect()")
public void doBefore(JoinPoint joinPoint){
System.out.println("执行前置通知");
}
@After("TestAspect()")
public void doAfter(JoinPoint joinPoint){
System.out.println("执行后置通知");
}
@AfterReturning("TestAspect()")
public void doAfterReturning(JoinPoint joinPoint){
System.out.println("执行返回后通知");
}
@AfterThrowing("TestAspect()")
public void deAfterThrowing(JoinPoint joinPoint){
System.out.println("执行抛出异常后通知");
}
@Around("TestAspect()")
public Object deAround(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("执行环绕通知!");
//继续执行被代理的方法
return joinPoint.proceed();
}
}
2.3 编写 controller 类
@RestController
public class TestAopController {
/**
* @GetMapping: 是一个组合注解,是 @RequestMapping(method=RequestMethod.GET) 的缩写
* @PostMapping:是一个组合注解,是 @RequestMapping(method=RequestMethod.POST) 的缩写
*/
@GetMapping("/aopIndex")
public String index() {
System.out.println("方法aopIndex执行");
return "hello world";
}
}
2.4 项目结构
三、测试
启动项目,在浏览器输入 http://localhost:8080/aopIndex
控制台的输出如下: