动态代理设计模式常用的有两种实现,一种是JDK自带的动态代理,另一种就是cglib的动态代理。
区别:JDK动态代理的被代理对象一定要有接口,通过动态生成接口实现类然后通过组合的方式实现在方法前后do something.
cglib通过继承的关系来实现在方法前后do something.
JDK动态代理的使用:
1.接口和实现类
public interface Service {
Integer getSum(Integer a, Integer b);
}
public class ServiceImpl implements Service {
public Integer getSum(Integer a, Integer b) {
return a + b;
}
}
2.代理处理类 需要实现Invocation接口
public class MyInvocationHandler implements InvocationHandler {
private Object object;
public MyInvocationHandler(Object object) {
this.object = object;
}
@Override
public Object invoke(Object paramObject, Method paramMethod,
Object[] paramArrayOfObject) throws Throwable {
System.out.println(paramMethod.getName() + "start......");
Object result = paramMethod.invoke(object, paramArrayOfObject);
System.out.println(paramMethod.getName() + "end......");
return result;
}
}
3.使用
public class Test {
public static void main(String[] args) {
Service service = new ServiceImpl();
MyInvocationHandler handler = new MyInvocationHandler(service);
Service proxy = (Service) Proxy.newProxyInstance(service.getClass()
.getClassLoader(), service.getClass().getInterfaces(), handler);
Integer result = proxy.getSum(1, 2);
System.out.println("result is " + result);
}
}