Spring中基于注解的AOP,借用了AspectJ中的注解,将代理逻辑“织入”被代理的目标类编译得到的字节码文件。由于生成的的是字节码码,因此上效果也是动态的。
动态代理:JDK原生实现方式,需要代理的目标类必须实现接口,因为此技术要求代理类和目标类实现了相同的接口(兄弟拜把子)。
cglib:通过继承目标类(认干爹),实现代理,所以不需要实现接口。
AspectJ:本质上是静态代理,将代理逻辑“织入”被代理的目标类编译得到的字节码文件,所以最终效果是动态的。weaver就是织入器。Spring只是借用了AspectJ中的注解。
需求:通过Spring中基于注解的AOP,来实现给计算器类中加减乘除方法增添日志。
step1:添加依赖
<!-- spring-aspects会帮我们传递过来aspectjweaver --><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>5.3.1</version></dependency>
step2:创建计算器类接口和实现类
package com.atguigu.spring.aop.annotation;/*** Date:2022/7/4* Author:ybc* Description:*/
public interface Calculator {int add(int i, int j);int sub(int i, int j);int mul(int i, int j);int div(int i, int j);}
@Component
public class CalculatorImpl implements Calculator {public int add(int i, int j) {int result = i + j;System.out.println("方法内部,result:"+result);return result;}public int sub(int i, int j) {int result = i - j;System.out.println("方法内部,result:"+result);return result;}public int mul(int i
本文发布于:2024-01-27 20:56:21,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17063602082591.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |