AOP执行流程与机制
一、CgLib实现动态代理的例子
1、创建Person类
package com.example.cglib; public class Person { public void study(){ System.out.println("study"); } }
2、创建CgLibProxy 类
package com.example.cglib; import java.lang.reflect.Method; import org.springframework.cglib.proxy.Enhancer; import org.springframework.cglib.proxy.MethodInterceptor; import org.springframework.cglib.proxy.MethodProxy; public class CgLibProxy implements MethodInterceptor { private Enhancer enhancer = new Enhancer(); public Object getProxy(Class<?> clazz){ enhancer.setSuperclass(clazz); enhancer.setCallback(this); Object object = enhancer.create(); return object; } @Override public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable { System.out.println(arg0.getClass().getName() +"." + arg1.getName()); //执行父类(目标对象Person)的对应方法 Object result = arg3.invokeSuper(arg0, arg2); System.out.println("执行结束"); return result; } public static void main(String[] args) { CgLibProxy proxy = new CgLibProxy(); Person person = (Person)proxy.getProxy(Person.class); System.out.println(person.getClass().getName()); //打印person父类的名字 System.out.println(person.getClass().getSuperclass().getName()); person.study(); } }
输出结果:
Cglib通过子类实现父类的方法实现AOP