mybatis運行原理03-mapper代理對象的獲取

上一篇文章中講述了DefaultSqlSession的創(chuàng)建過程。它可以利用executor來完成crud操作悠夯、管理數據庫連接和事務,也可以根據mapper類型來獲取mapper代理對象。sql的執(zhí)行放到后面講,本文先記錄一下mapper代理對象是如何生成的

    MemberDao mapper = sqlSession.getMapper(MemberDao.class);

當我們寫下getMapper(mapper.class)的時候尤筐,框架在后臺做了些什么事?實際上洞就,sqlSession本身是對mapper無感知的盆繁,所有關于mapper的信息,都在configuration屬性中旬蟋。所以getMapper先交給了configuration來完成油昂。

    public <T> T getMapper(Class<T> type) {
        return this.configuration.getMapper(type, this);
    }

在第一篇文章中說過,對mapper的解析完成后,以type:MapperProxyFactory(type)的形式將mapper的類型和產生對應代理對象的工廠存放到了mapperRegistry中的knowMapppers內冕碟,并將mapper的parameterMap稠腊、resultMap、statement等屬性以namespace: val的形式存到了對應的HashMap里鸣哀。然后在這里configuration.getMapper就將工作交給了mapperRegistry.同時,為了完成mapper與sqlSession的綁定吞彤,還將sqlSession作為參數傳遞了進來我衬。

    //委派給mapperRegistry完成
    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        return this.mapperRegistry.getMapper(type, sqlSession);
    }

看看mapperRegistry是如何獲取到mapper代理對象的吧。

// mapperRegistry.getMapper(...)
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory)this.knownMappers.get(type);
        if (mapperProxyFactory == null) {
            throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
        } else {
            try {
                return mapperProxyFactory.newInstance(sqlSession);
            } catch (Exception var5) {
                throw new BindingException("Error getting mapper instance. Cause: " + var5, var5);
            }
        }
    }

實際上饰恕,mapperRegistry并不承擔創(chuàng)建代理對象的職責挠羔,它的責任就是完成mapper的注冊。創(chuàng)建代理對象交給mapperProxyFactory來完成埋嵌。mapperProxyFactory內部mapperInterface用于封裝mapper的類型對象破加,methodCache則存放方法緩存。

public class MapperProxyFactory<T> {
    private final Class<T> mapperInterface;
    private final Map<Method, MapperMethodInvoker> methodCache = new ConcurrentHashMap();
    // ······
    protected T newInstance(MapperProxy<T> mapperProxy) {
        return Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);
    }

    public T newInstance(SqlSession sqlSession) {
        MapperProxy<T> mapperProxy = new MapperProxy(sqlSession, this.mapperInterface, this.methodCache);
        return this.newInstance(mapperProxy);
    }

重點關注代理對象的創(chuàng)建雹嗦,在這里首先調用的是 newInstance(SqlSession sqlSession)方法范舀,然后調newInstance(MapperProxy<T> mapperProxy),最后由Proxy.newProxyInstance()生成代理對象。至于這中間做了什么了罪,我們想想動態(tài)代理Proxy.newProxyInstance(...)是如何創(chuàng)建代理對象的吧锭环。

public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces,  InvocationHandler h)  throws IllegalArgumentException

Proxy.newProxyInstance(loader, interfaces, ih)需要三個參數: 被代理對象的類加載器loader、被代理對象的接口類型數組Class<?> [] interfaces泊藕、定義了方法調用邏輯的InvocationHandler h.

先思考一下:假設現在我們有一個類對象辅辩,需要創(chuàng)建一個能夠對它的方法進行增強的代理實例對象,該對象進行方法調用的邏輯在invocationHandler中,該如何創(chuàng)建這個代理對象呢娃圆?
咱也不知道哇玫锋,咱只知道動態(tài)代理...這里的invocationHandler不就有方法的實現邏輯嗎?我們只需要一個對象讼呢,把該對象方法的調用關聯給這個invocationHandler去做不就行了嗎撩鹿?
//todo : 動態(tài)代理ref:https://zhuanlan.zhihu.com/p/60805342

//invocationHandler.invoke(proxy, method, args)
public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable;
}

所以Proxy類就實現了這么一個功能:動態(tài)創(chuàng)建一個代理對象proxyObj,將對象與InvocationHandler ih關聯。然后當我們在程序中使用proxyObj.method(args)的時候吝岭,實際上就交給了ih.invoke(proxyObj, method, args)去處理三痰。

我們現在有了前兩個參數,但是當方法被調用時怎么進行處理的邏輯還沒有啊窜管。因此需要先創(chuàng)建一個InvocationHandler對象來,這個對象就是mapperProxy.他的構造方法很簡單散劫,就是將sqlSession, 接口和方法緩存關聯進來。沒什么好講的

public class MapperProxy<T> implements InvocationHandler, Serializable {
    private static final long serialVersionUID = -4724728412955527868L;
    private static final int ALLOWED_MODES = 15;
    private static final Constructor<Lookup> lookupConstructor;
    private static final Method privateLookupInMethod;
    private final SqlSession sqlSession;
    private final Class<T> mapperInterface;
    private final Map<Method, MapperProxy.MapperMethodInvoker> methodCache;

    public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperProxy.MapperMethodInvoker> methodCache) {
        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
        this.methodCache = methodCache;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            return Object.class.equals(method.getDeclaringClass()) ? method.invoke(this, args) : this.cachedInvoker(method).invoke(proxy, method, args, this.sqlSession);
        } catch (Throwable var5) {
            throw ExceptionUtil.unwrapThrowable(var5);
        }
    }
  //......
}

在newInstance(SqlSession sqlSession)時創(chuàng)建了mapperProxy幕帆,然后再使用Proxy.newInstance(interface.getClassLoader, new Class[]{interface}, mapperProxy)創(chuàng)建了一個對象获搏,并將該對象與mapperProxy進行了關聯,最后返回代理對象。如下。

public class MapperProxyFactory<T> {
    // ······
    protected T newInstance(MapperProxy<T> mapperProxy) {
        return Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);
    }

    public T newInstance(SqlSession sqlSession) {
        MapperProxy<T> mapperProxy = new MapperProxy(sqlSession, this.mapperInterface, this.methodCache);
        return this.newInstance(mapperProxy);
    }

至此常熙,xxxMapper = getMapper(xxxMapper.class)就結束了纬乍。我們拿到了代理對象,接下來的問題就是如何使用這個代理對象了裸卫,也就是當我們調用xxxMapper .xxxMethod()時仿贬,框架在后臺做了些什么。
to be continued.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末墓贿,一起剝皮案震驚了整個濱河市茧泪,隨后出現的幾起案子,更是在濱河造成了極大的恐慌聋袋,老刑警劉巖队伟,帶你破解...
    沈念sama閱讀 218,451評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現場離奇詭異幽勒,居然都是意外死亡嗜侮,警方通過查閱死者的電腦和手機,發(fā)現死者居然都...
    沈念sama閱讀 93,172評論 3 394
  • 文/潘曉璐 我一進店門啥容,熙熙樓的掌柜王于貴愁眉苦臉地迎上來锈颗,“玉大人,你說我怎么就攤上這事干毅∫瞬拢” “怎么了?”我有些...
    開封第一講書人閱讀 164,782評論 0 354
  • 文/不壞的土叔 我叫張陵硝逢,是天一觀的道長姨拥。 經常有香客問我,道長渠鸽,這世上最難降的妖魔是什么叫乌? 我笑而不...
    開封第一講書人閱讀 58,709評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮徽缚,結果婚禮上憨奸,老公的妹妹穿的比我還像新娘。我一直安慰自己凿试,他們只是感情好排宰,可當我...
    茶點故事閱讀 67,733評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著那婉,像睡著了一般板甘。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上详炬,一...
    開封第一講書人閱讀 51,578評論 1 305
  • 那天盐类,我揣著相機與錄音,去河邊找鬼。 笑死在跳,一個胖子當著我的面吹牛枪萄,可吹牛的內容都是我干的。 我是一名探鬼主播猫妙,決...
    沈念sama閱讀 40,320評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼瓷翻,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了割坠?” 一聲冷哼從身側響起逻悠,我...
    開封第一講書人閱讀 39,241評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎韭脊,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體单旁,經...
    沈念sama閱讀 45,686評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡沪羔,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,878評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了象浑。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蔫饰。...
    茶點故事閱讀 39,992評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖愉豺,靈堂內的尸體忽然破棺而出篓吁,到底是詐尸還是另有隱情,我是刑警寧澤蚪拦,帶...
    沈念sama閱讀 35,715評論 5 346
  • 正文 年R本政府宣布杖剪,位于F島的核電站,受9級特大地震影響驰贷,放射性物質發(fā)生泄漏盛嘿。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,336評論 3 330
  • 文/蒙蒙 一括袒、第九天 我趴在偏房一處隱蔽的房頂上張望次兆。 院中可真熱鬧,春花似錦锹锰、人聲如沸芥炭。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,912評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽园蝠。三九已至,卻和暖如春糕伐,著一層夾襖步出監(jiān)牢的瞬間砰琢,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,040評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留陪汽,地道東北人训唱。 一個月前我還...
    沈念sama閱讀 48,173評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像挚冤,于是被迫代替她去往敵國和親况增。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,947評論 2 355