* Created by j.tommy on 2017/9/10. */ publicinterface{ String request(); }
1 2 3 4 5 6 7 8 9
* Created by j.tommy on 2017/9/10. */ publicclassUserServiceimplements{ public String request(){ return"hello"; } }
1 2 3 4 5 6 7 8 9 10
* Created by j.tommy on 2017/9/10. */ publicclassMain{ publicstaticvoidmain(String[] args){ IUserService ius = new UserService(); String result = ius.request(); System.out.println("result:" + result); } }
静态代理
下面定义一个UserServiceProxy来代理UserService,对外提供服务。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
* Created by j.tommy on 2017/9/10. */ publicclassUserServiceProxyimplements{ private UserService us = null; public String request(){ // 延迟加载us的实例,在实际使用时初始化 if (null == us) { us = new UserService(); System.out.println("Created UserService."); } return us.request(); } }
测试类:
1 2 3 4 5 6 7 8 9 10 11 12
* Created by j.tommy on 2017/9/10. */ publicclassMain{ publicstaticvoidmain(String[] args){ // 通过代理类调用 IUserService ius = new UserServiceProxy(); System.out.println("Created proxy."); String result = ius.request(); System.out.println("result:" + result); } }
* jdk动态代理。 * Created by j.tommy on 2017/9/10. */ publicclassJdkDynamicProxyimplementsInvocationHandler{ // 真实对象 private Object target; publicJdkDynamicProxy(Object target){ this.target = target; } public Object invoke(Object proxy, Method method, Object[] args)throws Throwable { // 调用真实对象的方法 Object result = method.invoke(target,args); return result; } * 获取目标对象的代理对象 * @return */ public Object getProxy(){ return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),target.getClass().getInterfaces(),this); } }
测试类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
* Created by j.tommy on 2017/9/10. */ publicclassMain{ publicstaticvoidmain(String[] args){ // JDK动态代理 // 真实对象 IUserService ius = new UserService(); // 代理对象 IUserService us = (IUserService) new JdkDynamicProxy(ius).getProxy(); String result = us.request(); System.out.println("result:" + result); } }
* Created by j.tommy on 2017/9/10. */ publicclassCglibProxyimplementsMethodInterceptor{ private Enhancer enhancer = new Enhancer(); public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy)throws Throwable { // 通过代理类调用父类中的方法 return methodProxy.invokeSuper(o,args); } public Object getProxy(Class clazz){ // 设置需要创建之类的类 enhancer.setSuperclass(clazz); enhancer.setCallback(this);
// 通过字节码结束创建之类实例 return enhancer.create(); } }
测试类:
1 2 3 4 5 6 7 8 9 10 11
* Created by j.tommy on 2017/9/10. */ publicclassMain{ publicstaticvoidmain(String[] args){ CglibProxy cp = new CglibProxy(); UserService ius = (UserService) cp.getProxy(UserService.class); String result = ius.request(); System.out.println("result:" + result); } }