实体类
package com.mvc.rest;
public class CGLibTarget {
public void run(){
System.out.println("跑步");
}
public void speak(){
System.out.println("说英语");
}
}
代理类
package com.mvc.rest;
import java.lang.reflect.Method;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
public abstract class CGLibTargetProxy implements MethodInterceptor{
private Object target;
public Object createInstance(Object object){
this.target = object;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(this.target.getClass());
enhancer.setCallback(this);
enhancer.setClassLoader(this.target.getClass().getClassLoader());
return enhancer.create();
}
@Override
public Object intercept(Object proxy, Method method, Object[] args,MethodProxy methodProxy) throws Throwable {
Object result = null;
doBefore();
result = methodProxy.invokeSuper(proxy, args);
doAfter();
return result;
}
protected abstract void doBefore();
protected abstract void doAfter();
}
增强类
package com.mvc.rest;
public class CGLibTargetProxyAdvise extends CGLibTargetProxy{
@Override
protected void doBefore() {
System.out.println("start");
}
@Override
protected void doAfter() {
System.out.println("end");
}
}
测试类
package com.mvc.rest;
public class CGLibTargetTest {
public static void main(String args[]){
CGLibTarget target = new CGLibTarget();
CGLibTargetProxyAdvise proxy = new CGLibTargetProxyAdvise();
CGLibTarget obj = (CGLibTarget)proxy.createInstance(target);
obj.speak();
obj.run();
CGLibTargetProxyAdvise2 proxy2 = new CGLibTargetProxyAdvise2();
CGLibTarget obj2 = (CGLibTarget)proxy2.createInstance(target);
obj2.speak();
obj2.run();
}
}