引入包
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>3.2.12</version>
</dependency>
调用主类
public class Main {
public static void main(String[] args) {
Customer customer = (Customer)new MyMethodInterceptor().getInstance(Customer.class);
customer.getValue(1,2);
}
}
实现类
public class Customer {
public int getValue(int a, int b) {
System.out.println("a+b="+a+b);
return a+b;
}
}
cglib必须实现的类
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class MyMethodInterceptor implements MethodInterceptor {
public Object getInstance(Class<?> clazz){
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(clazz);
enhancer.setCallback(this);
return enhancer.create();
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
before();
Object object = methodProxy.invokeSuper(o,objects);
after();
return object;
}
private void before() {
System.out.println("before");
}
private void after() {
System.out.println("after");
}
}
为了深入研究spring aop 动态代理打下基础。