public interface InventoryService {public Inventory create(Inventory inventory);public List<Inventory> list();public Inventory findByVin(String vin);public Inventory update(Inventory inventory);public boolean delete(Long id);public Inventory compositeUpdateService(String vin, String newMake);
}
為該接口的實例創建動態代理的步驟如下:
1.創建一個java.lang.reflect.InvocationHandler的實例,它將負責代表實際服務實例處理方法調用,用于審核的示例Invocation處理程序如下:
...
public class AuditProxy implements java.lang.reflect.InvocationHandler {private Object obj;public static Object newInstance(Object obj) {return java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new AuditProxy(obj));}private AuditProxy(Object obj) {this.obj = obj;}public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {Object result;try {logger.info("before method " + m.getName());long start = System.nanoTime();result = m.invoke(obj, args);long end = System.nanoTime();logger.info(String.format("%s took %d ns", m.getName(), (end-start)) );} catch (InvocationTargetException e) {throw e.getTargetException(); } catch (Exception e) {throw new RuntimeException("unexpected invocation exception: " + e.getMessage());} finally {logger.info("after method " + m.getName());}return result;}
}
2.創建InventoryService實例時,返回一個代理,在本例中為AuditProxy,它構成InventoryService的實例,使用UML可以更好地解釋該代理:

這就是它在代碼中的樣子:
InventoryService inventoryService = (InventoryService)AuditProxy.newInstance(new DefaultInventoryService());
現在,對庫存服務的任何調用都將通過AuditProxy實例進行,該實例將在將實際方法調用委派給InventoryService實例的同時測量方法花費的時間。
那么代理用于:
1. Spring AOP廣泛使用它–它在內部為不同的AOP構造創建動態代理
2.如本例所示,對于任何類別的裝??飾,盡管AOP絕對適合這種用例 3.對于需要支持基于接口和注釋的功能的任何框架–甚至不需要真實的代理實例,動態代理可以基于通過注釋提供的一些元數據來重新創建接口的預期行為。
參考: all和雜物博客上的JCG合作伙伴 Biju Kunjummen 創建了Java動態代理 。
翻譯自: https://www.javacodegeeks.com/2012/08/creating-java-dynamic-proxy.html