MyBatis介面的簡單實現原理,mybatis介面原理

來源:互聯網
上載者:User

【轉】MyBatis介面的簡單實現原理,mybatis介面原理
MyBatis介面的簡單實現原理

用過MyBatis3的人可能會覺得為什麼MyBatis的Mapper介面沒有實作類別,但是可以直接用?

那是因為MyBatis使用Java動態代理實現的介面。

這裡僅僅舉個簡單例子來說明原理,不是完全針對MyBatis的,這種思想我們也可以應用在其他地方。

 

定義一個介面
public interface MethodInterface { String helloWorld(); }

 

實現動態代理介面
public class MethodProxy<T> implements InvocationHandler {    private Class<T> methodInterface;    public MethodProxy(Class<T> methodInterface) {        this.methodInterface = methodInterface;    }    @Override    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {        System.out.println("=========================");        System.out.println("方法名:" + method.getName());        //針對不同的方法進行不同的操作        return null;    }}

 

這裡針對invoke方法簡單說說MyBatis的實現原理,在該方法中,我們通過Method能夠擷取介面和方法名,介面的全名相當於MyBatis XML中的namespace,方法名相當於具體一個方法中的id。也就是說通過動態代理後,可以通過SqlSession來通過namespace.id方式來調用相應的方法。使用介面更方便,但是是一種間接的方式。

 

動態代理工廠類
public class MethodProxyFactory {    public static <T> T newInstance(Class<T> methodInterface) {        final MethodProxy<T> methodProxy = new MethodProxy<T>(methodInterface);        return (T) Proxy.newProxyInstance(                Thread.currentThread().getContextClassLoader(),                 new Class[]{methodInterface},                 methodProxy);    }}

通過該工廠類可以產生任意介面的動態代理類。

 

測試

 

MethodInterface method = MethodProxyFactory.newInstance(MethodInterface.class);method.helloWorld();
總結

一般談到動態代理我們通常的用法都是處理事務、日誌或者記錄方法執行效率等方面的應用。都是對實作類別方法的前置或者後置的特殊處理。

通過本文,其實可以看到另一種應用方向,那就是不需要實作類別,直接通過動態代理執行介面方法,MyBatis使用這種方式方便了我們調用方法,利用這種思路我們也許可以在別的方面做出一些更好的設計。

 

原文:http://blog.csdn.net/isea533/article/details/48296849

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.