文章出處
文章列表
在mybatis中,我們都只需要定義一個mapper接口,但并不需要對它進行任務實現。只要有對就的mapper.xml文件就可以訪問數據庫。那么,沒有接口的訪問是如何實現的呢。
答案就是JDK proxy.mybatis統一用代理類來寫接口實現。在代理類中,實現讀取配置文件并訪問數據庫存的操作。
現在我們來模擬一下,如何用代理類實現接口
1.定義接口,一個求各的方法
public interface FacadeCalculate { int add(int a,int b); }
2.定義一個handle類,繼承InvocationHandler。在invoke方法中,返回兩個參數相加的值。這里只是一個示例,并沒有作驗證和錯誤處理。
public class TraceHandler implements InvocationHandler { @Autowired private Calculate calculate; /** * Constructs a TraceHandler */ public TraceHandler() { } public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { return Integer.parseInt(args[0].toString()) + Integer.parseInt(args[1].toString()); } }
3.調用
public static void main(String[] args) { InvocationHandler handler = new TraceHandler(); FacadeCalculate proxy = (FacadeCalculate) Proxy.newProxyInstance(FacadeCalculate.class.getClassLoader(), new Class[] { FacadeCalculate.class }, handler); Integer result= proxy.add(2,3); System.out.println(result); }
輸出值會是5.
文章列表
全站熱搜