介绍
Spring动态代理可以选择使用jdk动态代理, 或者cglib动态代理, cglib动态代理位于 net.sf.cglib.proxy 包下.
使用时涉及
接口: net.sf.cglib.proxy.MethodInterceptor
用来生成动态子类的类类: net.sf.cglib.proxy.Enhancer
注意: cglib 动态代理是基于类的代理, 是通过对指定的业务类生成一个子类, 并覆盖其中业务方法实现代理. 因为使用继承, 所以被代理类不能使 final 修饰
使用步骤
1.创建MethodInterceptor接口的实现类, 并编写intercept方法的实现
2.通过methodProxy.invokeSuper(o, objects);调用父类的方法
3.创建Enhancer, 通过 setSuperclass(Class superclass)方法指定父类(被代理类), 通过 setCallback(final Callback callback)方法指定代理
4.enhancer.create() 生成代理, 调用被代理类的方法
代码演示
按照步骤编写简易逻辑代码.
创建MethodInterceptor接口的实现类
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
|
public class MyMethodInterceptor implements MethodInterceptor {
@Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("cglib动态代理 before . . .");
Object invoke = null; try { invoke = methodProxy.invokeSuper(o, objects); } catch (Throwable throwable) { throwable.printStackTrace(); System.err.println("cglib动态代理 error: " + throwable.getMessage()); } finally {
System.out.println("cglib动态代理 after . . ."); }
return invoke; } }
|
创建Enhancer
创建Enhancer, 通过 setSuperclass(Class superclass)方法指定父类(被代理类), 通过 setCallback(final Callback callback)方法指定代理
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class CglibMainTest {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(SubjectCglib.class); enhancer.setCallback(new MyMethodInterceptor());
SubjectCglib subjectCglib = (SubjectCglib) enhancer.create();
System.err.println(subjectCglib.getAge("liuzhihang")); }
}
|
可以将二者合并到MyInterceptor中
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
|
public class MyCglibInterceptor implements MethodInterceptor {
private Object object;
public Object getInstance(Object object) { this.object = object; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(object.getClass()); enhancer.setCallback(this);
return enhancer.create(); }
@Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("cglib动态代理 before . . .");
Object invoke = null; try { invoke = methodProxy.invokeSuper(o, objects); } catch (Throwable throwable) { throwable.printStackTrace(); System.err.println("cglib动态代理 error: " + throwable.getMessage()); } finally {
System.out.println("cglib动态代理 after . . ."); }
return invoke; } }
|