Spring注解配置AOP導(dǎo)致通知執(zhí)行順序紊亂解決方案
今天在測試Spring的AOP時,發(fā)現(xiàn)使用注解配置AOP的方式會導(dǎo)致通知的執(zhí)行順序紊亂。【最終通知居然在異常通知之前執(zhí)行了】
測試代碼
(1)定義TargetInterface目標(biāo)接口
public interface TargetInterface {public abstract void targetProxy();}
(2)定義TargetImpl目標(biāo)類
@Component('target')public class TargetImpl implements TargetInterface {public void targetProxy() { System.out.println('target proxy ......'); int i = 1/0;//異常}}
(3)定義切面類(內(nèi)含增強方法)
@Component('myAspect')//定義切面類@Aspect//聲明當(dāng)前類是切面類public class TargetAspect {//定義切點表達(dá)式@Pointcut('execution(* com.ahzyy.target.impl.*.*(..))')public void pt() {}@Before('pt()')public void before() { System.out.println('前置通知......');}@After('pt()')public void after() { System.out.println('最終通知......');}@AfterReturning('pt()')public void afterReturning() { System.out.println('后置通知......');}@AfterThrowing('pt()')public void afterThrowing() { System.out.println('異常通知......');}}
(4)配置applicationContextAnno.xml文件
<!--配置組件掃描的包--><context:component-scan base-package='com.ahzyy'/><!--配置AOP自動代理--><aop:aspectj-autoproxy/>
(5)定義測試類
@RunWith(SpringJUnit4ClassRunner.class)//@ContextConfiguration('classpath:applicationContext.xml')@ContextConfiguration('classpath:applicationContextAnno.xml')public class AopTest {@Autowiredprivate TargetInterface target;@Testpublic void test01() { target.targetProxy();}}
(6)運行結(jié)果:
【最終通知在異常通知之前執(zhí)行了!!!】
(7)解決方法:
(7.1)使用xml配置方式配置AOP;
(7.2)注解使用@Around(環(huán)繞通知)方式配置AOP(修改TargetAspect類使用環(huán)繞通知);
@Component('myAspect')//定義切面類@Aspect//聲明當(dāng)前類是切面類public class TargetAspect {//定義切點表達(dá)式@Pointcut('execution(* com.ahzyy.target.impl.*.*(..))')public void pt() {}@Around('pt()')public Object aroundNotice(ProceedingJoinPoint pjp) { System.out.println('環(huán)繞通知'); Object result = null; before();//前置通知 try { result = pjp.proceed(); afterReturning();//后置通知 } catch (Throwable throwable) {afterThrowing();//異常通知 throwable.printStackTrace(); } after();//最終通知 return result;}public void before() { System.out.println('前置通知......');}public void afterReturning() { System.out.println('后置通知......');}public void afterThrowing() { System.out.println('異常通知......');}public void after() { System.out.println('最終通知......');}}
(7.3)運行結(jié)果
[運行順序正確]
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 利用ajax+php實現(xiàn)商品價格計算2. JavaScript中的for循環(huán)與雙重for循環(huán)詳解3. vue項目登錄成功拿到令牌跳轉(zhuǎn)失敗401無登錄信息的解決4. 詳解PHP結(jié)構(gòu)型設(shè)計模式之橋接模式Bridge Pattern5. JSP出現(xiàn)中文亂碼問題解決方法詳解6. 詳解如何使用Net將HTML簡歷導(dǎo)出為PDF格式7. 如何將asp.net core程序部署到Linux服務(wù)器8. 表單中Readonly和Disabled的區(qū)別詳解9. 通用 HTTP 簽名組件的另類實現(xiàn)方式10. ThinkPHP5實現(xiàn)JWT Token認(rèn)證的過程(親測可用)
