java动态代理与CGLib代理示例代码

被代理服务接口定义与实现

接口定义


public interface Hello {
   void sayHello();
}

服务实现


public class HelloImpl implements Hello {

   @Override
   public void sayHello() {
       System.out.println("hello world");
   }
}

动态代理类


public class DynamicProxy implements InvocationHandler {

   private Object target;

   public DynamicProxy(Object target) {
       this.target = target;
   }

   @Override
   public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
       before();
       Object result = method.invoke(target, args);
       after();
       return result;
   }

   private void before() {
       System.out.println("before");
   }

   private void after() {
       System.out.println("result");
   }
}

使用


public static void main(String[] args) {
   Hello hello1 = new HelloImpl();
   Hello hello2 = new HelloImpl2();
   List helloList = new ArrayList();
   helloList.add(hello1);
   helloList.add(hello2);
   for (Hello hello : helloList) {
       Hello helloProxy = getHelloService(hello);
       helloProxy.sayHello();
   }
}

public static Hello getHelloService(Hello hello) {
   DynamicProxy dynamicProxy = new DynamicProxy(hello);
   return (Hello)Proxy.newProxyInstance(
           hello.getClass().getClassLoader(),
           hello.getClass().getInterfaces(),
           dynamicProxy);
}

CGLib代理


public class CGLibProxy implements MethodInterceptor {

   private static CGLibProxy instance = new CGLibProxy();

   public static CGLibProxy getInstance() {
       return instance;
   }

   public  T getProxy(Class cls) {
       return (T) Enhancer.create(cls, this);
   }

   public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
       before();
       Object result = proxy.invokeSuper(obj, args);
       after();
       return result;
   }

   private void before() {
       System.out.println("before");
   }

   private void after() {
       System.out.println("result");
   }
}

使用


public class App {
   public static void main(String[] args) {
       Hello helloProxy = CGLibProxy.getInstance().getProxy(HelloImpl.class);
       helloProxy.sayHello();
   }
}

你可能感兴趣的:(java动态代理与CGLib代理示例代码)