1. AOP使用案例
1. 导入AOP依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.6.4</version>
</dependency>
2.编写测试方法入口
@RestController
public class TestController {
@RequestMapping(value = "/testAop", method = RequestMethod.POST)
public void testAop() {
System.out.println("testAop方法");
}
}
3. 编写AOP方法
@Aspect
@Component
public class AopController {
@Pointcut("execution(* com.szk.test..*(..))")
public void controllerPointCut(){
}
@Before("controllerPointCut()")
public void before(){
System.out.println("进入前");
}
@After("controllerPointCut()")
public void after(){
System.out.println("进入后");
}
@Around("controllerPointCut()")
public void round(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("环绕前");
joinPoint.proceed();
System.out.println("环绕后");
}
4.启动项目,用postman调用方法打印结构
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b6538da25f81dcd3a9c398a641e06f64.png)
2.自定义注解
1. 导入AOP依赖上面的一样
2. 测试方法入口(把自定义的注解添加到方法上)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/318cda3783f9c8a8d1e72e6596f74404.png)
3. 切入点配置做一下调整,指向自定义的注解
@Aspect
@Component
public class AopController {
@Pointcut("@annotation(com.szk.test.TestInterface)")
public void controllerPointCut(){
}
@Before("controllerPointCut()")
public void before(){
System.out.println("自定义注解进入前");
}
@After("controllerPointCut()")
public void after(){
System.out.println("自定义注解进入后");
}
@Around("controllerPointCut()")
public void round(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("自定义注解环绕前");
joinPoint.proceed();
System.out.println("自定义注解环绕后");
}
}
2.调用打印日志
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/560ae68e603a78e4e1f51b74f9312166.png)