Spring aop 如何通過獲取代理對象實(shí)現(xiàn)事務(wù)切換
在項(xiàng)目中,涉及到同一個(gè)類中一個(gè)方法調(diào)用另外一個(gè)方法,并且兩個(gè)方法的事務(wù)不相關(guān),
這里面涉及到一個(gè)事務(wù)切換的問題,一般的方法沒問題,根據(jù)通過aop注解在方法上通過加注解標(biāo)識(shí),
答案是:通過spring aop類里面的AopContext類獲取當(dāng)前類的代理對象,
這樣就能切換對應(yīng)的事務(wù)管理器了,具體做法如下:
(1).在applicationContext.xml文件中配置如下:<!-- 開啟暴露Aop代理到ThreadLocal支持 --> <aop:aspectj-autoproxy expose-proxy='true'/> (2).在需要切換的地方獲取代理對象,
再調(diào)用對應(yīng)的方法,如下:
((類名) AopContext.currentProxy()).方法(); (3).注意
這里需要被代理對象使用的方法必須是public類型的方法,不然獲取不到代理對象,會(huì)報(bào)下面的錯(cuò)誤:
java.lang.IllegalStateException: Cannot find current proxy: Set ’exposeProxy’ property on Advised to ’true’ to make it available.
開啟暴露AOP代理即可.
因?yàn)殚_啟事務(wù)和事務(wù)回滾,實(shí)際這個(gè)過程是aop代理幫忙完成的,當(dāng)調(diào)用一個(gè)方法時(shí),它會(huì)先檢查時(shí)候有事務(wù),有則開啟事務(wù),
當(dāng)調(diào)用本類的方法是,它并沒有將其視為proxy調(diào)用,而是方法的直接調(diào)用,所以也就沒有檢查該方法是否含有事務(wù)這個(gè)過程,
那么本地方法調(diào)用的事務(wù)也就無效了。
獲取代理bean的原始對象public class AopTargetUtil { /** * 獲取 目標(biāo)對象 * @param proxy 代理對象 * @return * @throws Exception */ public static Object getTarget(Object proxy) throws Exception { if(!AopUtils.isAopProxy(proxy)) { return proxy;//不是代理對象 } if(AopUtils.isJdkDynamicProxy(proxy)) { return getJdkDynamicProxyTargetObject(proxy); } else { //cglib return getCglibProxyTargetObject(proxy); } } private static Object getCglibProxyTargetObject(Object proxy) throws Exception { Field h = proxy.getClass().getDeclaredField('CGLIB$CALLBACK_0'); h.setAccessible(true); Object dynamicAdvisedInterceptor = h.get(proxy); Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField('advised'); advised.setAccessible(true); Object target = ((AdvisedSupport)advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget(); return target; } private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception { Field h = proxy.getClass().getSuperclass().getDeclaredField('h'); h.setAccessible(true); AopProxy aopProxy = (AopProxy) h.get(proxy); Field advised = aopProxy.getClass().getDeclaredField('advised'); advised.setAccessible(true); Object target = ((AdvisedSupport)advised.get(aopProxy)).getTargetSource().getTarget(); return target; }}
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP動(dòng)態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享2. jsp文件下載功能實(shí)現(xiàn)代碼3. asp.net core項(xiàng)目授權(quán)流程詳解4. 在JSP中使用formatNumber控制要顯示的小數(shù)位數(shù)方法5. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫特效6. XMLHTTP資料7. ASP常用日期格式化函數(shù) FormatDate()8. html中的form不提交(排除)某些input 原創(chuàng)9. CSS3中Transition屬性詳解以及示例分享10. ASP基礎(chǔ)入門第八篇(ASP內(nèi)建對象Application和Session)
