一、proxy 动态代理
面向接口
1 必须有接口和实现类
2 增强接口中定义的方法
3 只能读取接口中方法的上注解
二、cglib动态代理模式
面向父类 解决了JDK 动态代理的缺点与不足。
要依赖第三方JAR包
<dependencies> <!--这个里面包括了所需的jar包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.25</version> </dependency> <!--用于测试--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> </dependencies>
public class Person {
public Person(){
}
public void eat(String foodName){
System.out.println("张三吃 "+ foodName);
}
}
public class Test {
public static void main(String[] args) {
Person person = new Person();
//1. 获得一个enhancer对象
Enhancer enhancer = new Enhancer();
//2. 设置父类字节码
enhancer.setSuperclass(person.getClass());
//3. 获得MethodInterceptor 对象,用于定义增强规则
MethodInterceptor methodInterceptor = new MethodInterceptor() {
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
/**
* Object o 生成之后的代理对象 personProxy
* Method method 父类中原本要执行的方法
* Object[] objects 方法调用时,传入的实参数组
* MethodProxy methodProxy 子类重写父类的方法
*/
Object res = null;
if (method.getName().equals("eat")){
System.out.println("饭前洗手");
res = methodProxy.invokeSuper(o,objects);
System.out.println("饭后刷碗");
}else{
res = methodProxy.invokeSuper(o,objects);
}
return res;
}
};
//4. 设置methodInterceptor
enhancer.setCallback(methodInterceptor);
//5. 获得代理对象
Person personProxy = (Person) enhancer.create();
//6. 使用 代理对象完成 功能
personProxy.eat("包子");
}
}