文章出處

在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.

點我下載代碼


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()