静态代理

静态代理就是我们自己写代理类,在代理类中实现代理:

  1. public class StaticProxy implements IRentingHouse{
  2. private IRentingHouse rentingHouse;
  3. public StaticProxy(IRentingHouse rentingHouse) {
  4. this.rentingHouse = rentingHouse;
  5. }
  6. @Override
  7. public void rentingHouse() {
  8. rentingHouse.rentingHouse();
  9. }
  10. }

动态代理

JDK动态代理

  1. public class JdkProxy {
  2. private static JdkProxy jdkProxy = new JdkProxy();
  3. private JdkProxy() {
  4. }
  5. public static JdkProxy getInstance() {
  6. return jdkProxy;
  7. }
  8. public Object getProxyByObj(Object obj) {
  9. Object result = Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), (proxy, method, args) -> {
  10. System.out.println("增强方法前");
  11. Object invoke = method.invoke(obj, args);
  12. System.out.println("增强方法后");
  13. return invoke;
  14. });
  15. return result;
  16. }
  17. public <T> T getProxyByClass(Class<T> clazz) {
  18. Object result = Proxy.newProxyInstance(JdkProxy.class.getClassLoader(), new Class[]{clazz}, (proxy, method, args) -> {
  19. System.out.println("增强方法前");
  20. Object invoke = method.invoke(clazz, args);
  21. System.out.println("增强方法后");
  22. return invoke;
  23. });
  24. return (T) result;
  25. }
  26. public static void main(String[] args) {
  27. IRentingHouse rentingHouse = new MyRentingHouse();
  28. // jdk
  29. IRentingHouse proxy = (IRentingHouse) JdkProxy.getInstance().getProxyByObj(rentingHouse);
  30. proxy.rentingHouse();
  31. }
  32. }

CgLib动态代理

  1. public class CgLibProxy {
  2. private static CgLibProxy cgLibProxy = new CgLibProxy();
  3. private CgLibProxy() {
  4. }
  5. public static CgLibProxy getInstance() {
  6. return cgLibProxy;
  7. }
  8. public Object getProxyObject(Object obj) {
  9. return Enhancer.create(obj.getClass(), (MethodInterceptor) (o1, method, objects, methodProxy) -> {
  10. System.out.println("方法增强前");
  11. Object invoke = method.invoke(obj, objects);
  12. System.out.println("方法增强后");
  13. return invoke;
  14. });
  15. }
  16. public static void main(String[] args) {
  17. IRentingHouse rentingHouse = new MyRentingHouse();
  18. // cglib
  19. IRentingHouse proxy = (IRentingHouse) CgLibProxy.getInstance().getProxyObject(rentingHouse);
  20. proxy.rentingHouse();
  21. }
  22. }

总结

静态代理和动态代理的区别

唯一区别就是静态代理需要手写代理类,而动态代理是不需要的,我们虽然在动态代理的时候写了类,但这个类只是为了更好的实现一个代码的解耦,不需要也是可以的。

JDK动态代理与CgLib动态代理

区别在于JDk动态代理必须实现接口,因为在Proxy在生成代理对象的时候我们需要使用接口类;而CgLib动态代理不需要代理类去实现接口,传递当前对象即可。