基于jdk的动态代理和基于cglib的动态代理实现方式。
基于jdk的动态代理(有接口)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| public interface User { void save(); }
class UserImpl implements User{ public void save(){ System.out.println("save running......"); } }
class UserAdvice{ public void before(){ System.out.println("before save"); }
public void after(){ System.out.println("after save"); } }
class ProxyFactory{ public static Object getProxy(){ MyInvocationHandler handler = new MyInvocationHandler(); User user = new UserImpl(); UserAdvice userAdvice = new UserAdvice(); handler.setAdvice(userAdvice); handler.setObj(user); return Proxy.newProxyInstance(user.getClass().getClassLoader(), user.getClass().getInterfaces(),handler); } }
class MyInvocationHandler implements InvocationHandler{ private Object obj; public void setObj(Object obj){ this.obj = obj; } private UserAdvice advice; public void setAdvice(UserAdvice advice){ this.advice = advice; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { advice.before(); Object invoke = method.invoke(obj, args); advice.after(); return invoke; } }
class Test{ public static void main(String[] args) { User proxy = (User) ProxyFactory.getProxy(); proxy.save(); } }
|
基于cglib的动态代理(无接口)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| public class Target {
public void save(){ System.out.println("save running......"); } }
class Advice{ public void before(){ System.out.println("save before"); }
public void after(){ System.out.println("save after"); } }
class Test{ public static void main(String[] args) { Target target = new Target(); Advice advice = new Advice(); Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(Target.class); enhancer.setCallback(new MethodInterceptor() { @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { advice.before(); Object invoke = method.invoke(target, args); advice.after(); return invoke; } }); Target proxy = (Target) enhancer.create(); proxy.save(); } }
|