刚开始使用这个函数时候也就是有样画样,并不太了解这个代理函数的深入含义,知道在做远程调用接口规范是才发现这个行数的妙用。废话不多说,先来看段代码。
接口1 public interface EvgServiceBackendApi { /** * Get backend menus * @auth XiaoMing.hu * @return */ @GetMapping("/getMenus") CommonResponse<String> getMenus(); }
接口2 public interface HealthApi { Response<String> getMenus(); Response<RequestDto> testGet(); }
Object object = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{EvgServiceBackendApi.class,HealthApi.class}, (proxy, method, args) -> { //TODO 实现远程调用逻辑,proxy是代理本身,method是接口方法,args是相应接口参数 System.out.println(method); return null; }); EvgServiceBackendApi evgServiceBackendApi = (EvgServiceBackendApi)object; evgServiceBackendApi.getMenus(); HealthApi healthApi = (HealthApi) object; healthApi.testGet("","");
通过上面代码总结如下:
1、代理函数可以同时设置成对个类的代理
2、 这样做的意义是什么呢,就是作为远程调用的接口的约束。(远程服务,直接把自己实现的接口给开放出来给客户端引用,并通过代理来实现远程调用逻辑即可)