本文分享自华为云社区《Spring高手之路20——深入理解@EnableAspectJAutoProxy的力量》,作者: 砖业洋__。
1. 初始调试代码
面向切面编程(AOP)是一种编程范式,用于增强软件模块化,通过将横切关注点(如事务管理、安全等)分离出业务逻辑。Spring AOP是Spring框架中实现AOP的一种方式,它通过代理机制在运行时向对象动态地添加增强。AspectJ是一种更强大的AOP实现,它通过编译时和加载时织入,提供了比Spring AOP更丰富的增强选项。本文将探索如何通过Spring AOP进行简单的AOP配置和实现。
后续源码分析就用这个前置通知的代码调试
package com.example.demo.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Aspect @Component public class MyAspect { @Before("execution(* com.example.demo.service.MyService.performAction(..))") public void beforeAdvice(JoinPoint joinPoint) { System.out.println("Before method: " + joinPoint.getSignature().getName()); } }
package com.example.demo.configuration; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration @EnableAspectJAutoProxy public class AppConfig { }
package com.example.demo.service; import org.springframework.stereotype.Service; // 一个简单的服务类 @Service public class MyService { public void performAction() { System.out.println("Performing an action"); } }
package com.example.demo; import com.example.demo.service.MyService; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; //主应用类 @ComponentScan(basePackages = "com.example.demo") public class DemoApplication { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoApplication.class); MyService myService = context.getBean(MyService.class); myService.performAction(); // 调用方法,触发AOP增强 } }
2. 源码跟踪分析
2.1 初探@EnableAspectJAutoProxy
上面代码中,AppConfig配置类里有个@EnableAspectJAutoProxy注解,前面说过,@EnableAspectJAutoProxy注解告诉Spring框架去寻找带有@Aspect注解的类,Spring AOP通过读取@EnableAspectJAutoProxy注解的属性来配置代理的行为。
下面用时序图来展示通过@EnableAspectJAutoProxy注解启用面向切面编程(AOP)的过程。
