基于jdk的动态代理
package com.tuy.proxy.jdk;
public interface TargetInterface {
public void save();
}
package com.tuy.proxy.jdk;
public class Target implements TargetInterface{
public void save() {
System.out.println("save running");
}
}
package com.tuy.proxy.jdk;
public class Advice {
public void before()
{
System.out.println("前置增强。。。。。。。");
}
public void afterRunning()
{
System.out.println("后置增强。。。。。。。");
}
}
package com.tuy.proxy.jdk;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyTest {
//基于jdk的动态代理,目标对象必须继承一个接口
//在不改变原来方法的情况下,对目标方法进行增强
public static void main(String[] args) {
//目标对象
final Target target=new Target();
//增强对象
final Advice advice =new Advice();
//返回值 就是动态生成的代理对象
TargetInterface proxy= (TargetInterface) Proxy.newProxyInstance(
target.getClass().getClassLoader(), //目标对象加载器
target.getClass().getInterfaces(), //目标对象相同的接口字节码对象数组
new InvocationHandler() {
//调用代理对象的任何方法,实质执行的都是Invoke方法
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//前置增强
advice.before();
Object res= method.invoke(target,args); //执行方法
//后置对象
advice.afterRunning();
return res;
}
}
);
//调用代理对象的方法, 接口有什么方法 ,代理对象就有什么方法
proxy.save();
}
}
基于cglib的动态代理
package com.tuy.proxy.cglib;
public class Target {
public void save() {
System.out.println("save running");
}
}
package com.tuy.proxy.cglib;
public class Advice {
public void before()
{
System.out.println("前置增强。。。。。。。");
}
public void afterRunning()
{
System.out.println("后置增强。。。。。。。");
}
}
package com.tuy.proxy.cglib;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class ProxyTest {
//基于cglib的动态代理, 需要导入 spring框架(比较高的版本才有cglib包)
//在不改变原来方法的情况下,对目标方法进行增强
public static void main(String[] args) {
//目标对象
final Target target=new Target();
//增强对象
final Advice advice =new Advice();
//1、 创建增强器
Enhancer enhancer=new Enhancer();
//2 设置父类(目标)
enhancer.setSuperclass(Target.class);
//3 设置回调
enhancer.setCallback(new MethodInterceptor() {
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
//前置增强
advice.before();
Object res= method.invoke(target,args); //执行目标方法
//后置对象
advice.afterRunning();
return null;
}
});
//4 创建代理对象
Target proxy= (Target) enhancer.create();
proxy.save();
}
}