#Spring AOPjava
#一. AOP概念spring
AOP即面向切面編程,是OOP編程的有效補充。使用AOP技術,能夠將一些系統性相關的編程工做,獨立提取出來,獨立實現,而後經過切面切入進系統。從而避免了在業務邏輯的代碼中混入不少的系統相關的邏輯——好比權限管理,事物管理,日誌記錄等等。express
切面(Aspect)編程
切入系統的一個切面。好比事務管理是一個切面,權限管理也是一個切面this
切入點(Pointcut).net
符合切點表達式的鏈接點,也就是真正被切入的地方日誌
鏈接點(Joinpoint)code
能夠進行橫向切入的位置事務
通知(Advice)get
切面在某個鏈接點執行的操做(分爲: Before advice , After returning advice , After throwing advice , After (finally) advice , Around advice)
#二. 代碼示例
1.基於註解的實現-日誌切面類
[@Aspect](http://my.oschina.net/aspect) //定義切面類 public class LogAnnotationAspect { @SuppressWarnings("unused") //定義切入點 @Pointcut("execution(* com.test.service.*.*(..))") private void allMethod(){} //針對指定的切入點表達式選擇的切入點應用前置通知 @Before("execution(* com.test.service.*.*(..))") public void before(JoinPoint call) { String className = call.getTarget().getClass().getName(); String methodName = call.getSignature().getName(); System.out.println("【註解-前置通知】:" + className + "類的" + methodName + "方法開始了"); } //訪問命名切入點來應用後置通知 @AfterReturning("allMethod()") public void afterReturn() { System.out.println("【註解-後置通知】:方法正常結束了"); } //應用最終通知 @After("allMethod()") public void after(){ System.out.println("【註解-最終通知】:無論方法有沒有正常執行完成," + "必定會返回的"); } //應用異常拋出後通知 @AfterThrowing("allMethod()") public void afterThrowing() { System.out.println("【註解-異常拋出後通知】:方法執行時出異常了"); } //應用周圍通知 //@Around("allMethod()") public Object doAround(ProceedingJoinPoint call) throws Throwable{ Object result = null; this.before(call);//至關於前置通知 try { result = call.proceed(); this.afterReturn(); //至關於後置通知 } catch (Throwable e) { this.afterThrowing(); //至關於異常拋出後通知 throw e; }finally{ this.after(); //至關於最終通知 } return result; } }
2.聲明式事務
//聲明事務處理器 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> // 聲明事務通知 <tx:advice id="bookShopTx" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="purchase" propagation="REQUIRES_NEW" isolation="READ_COMMITTED" rollback-for="java.lang.ArithmeticException"/> </tx:attributes> </tx:advice> //聲明事務通知須要通知哪些類的那些方法, 即: 那些方法受事務管理 <aop:config> //聲明切入點 <aop:pointcut expression="execution(* cn.partner4java.spring.transaction.BookShopService.*(..))" id="txPointCut"/> //把切入點和事務通知聯繫起來: 既聲明一個加強器 <aop:advisor advice-ref="bookShopTx" pointcut-ref="txPointCut"/> </aop:config>