ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 第一步 开启aop支持 ~~~ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration @ComponentScan("cn.maicaii.*") /** * 目标对象实现了接口 – 使用CGLIB代理机制 * 目标对象没有接口(只有实现类) – 使用CGLIB代理机制 * false * 目标对象实现了接口 – 使用JDK动态代理机制(代理所有实现了的接口) * 目标对象没有接口(只有实现类) – 使用CGLIB代理机制 */ @EnableAspectJAutoProxy(proxyTargetClass = true) // 第一步 开启aop public class Config { } ~~~ ## 第二部 导入apo jar包 ~~~ <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.7</version> </dependency> ~~~ ## 第三步 编写切面类 ~~~ import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; /** * 切面类 */ @Component @Aspect // 需要导入 aspectjweaver 包 public class UserAspect { /** * 切点 */ @Pointcut("execution(* cn.maicaii.service.*.*(..))") public void pointcut() { } /** * 执行之前 */ @Before("pointcut()") public void before(JoinPoint joinPoint) { System.out.println("执行方法之前执行"); } /** * 当匹配的方法执行 正常 返回时运行。 在 After 之后 */ @AfterReturning(pointcut = "pointcut()", returning = "retVal") public void afterReturning(Object retVal) { System.out.println(retVal); System.out.println("执行方法正常 返回时运行时 执行"); } /** * 执行之后 */ @After("pointcut()") public void after() { System.out.println("执行方法之后执行"); } /** * 当匹配的方法执行通过抛出异常退出时,抛出通知运行后。您可以使用@AfterThrowing注解来声明它 */ @AfterThrowing("pointcut()") public void afterThrowing(){ System.out.println("执行方法时有异常时执行"); } /** * 环绕通知 */ @Around("pointcut()") public void around(ProceedingJoinPoint point) throws Throwable { System.out.println("环绕通知之前"); point.proceed(); System.out.println("环绕通知之后"); } } ~~~