目录
AspectJ是Java社区里最完整最流行的AOP框架。
在Spring2.0以上版本中,可以使用基于AspectJ注解或基于XML配置的AOP。
添加jar包支持
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-aspectsartifactId>
- <version>5.3.1version>
- dependency>
配置文件
开启组件扫描
开启AspectJ注解支持
- <context:component-scan base-package="com.haogu">context:component-scan>
- <aop:aspectj-autoproxy>aop:aspectj-autoproxy>
将MyLogging类上面添加注解
@Component:将当前类标识为一个组件
@Aspect:将当前类标识为切面类【非核心业务提取类】
将MyLogging中的方法中添加通知注解
@Before
- /**
- * @author Lee
- * @create 2022/3/28 16:03
- */
- @Component //将当前类标识为一个组件
- @Aspect //将当前类标识为【切面类】【非核心业务提取类】
- public class MyLogging {
- /**
- * 方法之前
- */
- @Before(value = "execution(public int com.haogu.controller.HelloController.add(int, int) )")
- public void beforeMethod(JoinPoint joinPoint){
- //获取方法名称
- String methodName = joinPoint.getSignature().getName();
- //获取参数
- Object[] args = joinPoint.getArgs();
- System.out.println("==>Calc中"+methodName+"方法(),参数:"+ Arrays.toString(args));
- }
- }
测试
- public void testAop(){
- //创建容器对象
- ApplicationContext context =
- new ClassPathXmlApplicationContext("applicationContext_aop.xml");
- HelloController hello = context.getBean(HelloController.class);
- int add = calc.add(1, 2);
-
- }
AOP:Aspect-Oriented Programming,面向切面编程【面向对象一种补充】
优势:
解决代码分散问题
解决代码混乱问题
OOP:Object-Oriented Programming,面向对象编程
横切