Spring aop 如何通過(guò)獲取代理對(duì)象實(shí)現(xiàn)事務(wù)切換
在項(xiàng)目中,涉及到同一個(gè)類中一個(gè)方法調(diào)用另外一個(gè)方法,并且兩個(gè)方法的事務(wù)不相關(guān),
這里面涉及到一個(gè)事務(wù)切換的問(wèn)題,一般的方法沒(méi)問(wèn)題,根據(jù)通過(guò)aop注解在方法上通過(guò)加注解標(biāo)識(shí),
答案是:通過(guò)spring aop類里面的AopContext類獲取當(dāng)前類的代理對(duì)象,
這樣就能切換對(duì)應(yīng)的事務(wù)管理器了,具體做法如下:
(1).在applicationContext.xml文件中配置如下:<!-- 開(kāi)啟暴露Aop代理到ThreadLocal支持 --> <aop:aspectj-autoproxy expose-proxy='true'/> (2).在需要切換的地方獲取代理對(duì)象,
再調(diào)用對(duì)應(yīng)的方法,如下:
((類名) AopContext.currentProxy()).方法(); (3).注意
這里需要被代理對(duì)象使用的方法必須是public類型的方法,不然獲取不到代理對(duì)象,會(huì)報(bào)下面的錯(cuò)誤:
java.lang.IllegalStateException: Cannot find current proxy: Set ’exposeProxy’ property on Advised to ’true’ to make it available.
開(kāi)啟暴露AOP代理即可.
因?yàn)殚_(kāi)啟事務(wù)和事務(wù)回滾,實(shí)際這個(gè)過(guò)程是aop代理幫忙完成的,當(dāng)調(diào)用一個(gè)方法時(shí),它會(huì)先檢查時(shí)候有事務(wù),有則開(kāi)啟事務(wù),
當(dāng)調(diào)用本類的方法是,它并沒(méi)有將其視為proxy調(diào)用,而是方法的直接調(diào)用,所以也就沒(méi)有檢查該方法是否含有事務(wù)這個(gè)過(guò)程,
那么本地方法調(diào)用的事務(wù)也就無(wú)效了。
獲取代理bean的原始對(duì)象public class AopTargetUtil { /** * 獲取 目標(biāo)對(duì)象 * @param proxy 代理對(duì)象 * @return * @throws Exception */ public static Object getTarget(Object proxy) throws Exception { if(!AopUtils.isAopProxy(proxy)) { return proxy;//不是代理對(duì)象 } 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. 讓chatgpt將html中的圖片轉(zhuǎn)為base64方法示例2. PHP設(shè)計(jì)模式中觀察者模式講解3. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說(shuō)明4. ASP基礎(chǔ)知識(shí)Command對(duì)象講解5. asp畫中畫廣告插入在每篇文章中的實(shí)現(xiàn)方法6. JSP中param動(dòng)作的實(shí)例詳解7. ASP新手必備的基礎(chǔ)知識(shí)8. JSP的setProperty的使用方法9. chat.asp聊天程序的編寫方法10. PHP實(shí)現(xiàn)圖片旋轉(zhuǎn)的方法詳解
