AOP (面向切面編程) :在程序運行時,動態的將代碼塊切入到某個類的某個方法的某個位置(前面、后面、發生異常時)上。
前置通知:在某個方法之前執行 實現MethodBeforeAdvice接口
后置通知:在某個方法之后執行 實現AfterReturningAdvice接口
異常通知:在某個方法發生異常時執行 實現ThrowsAdvice接口
環繞通知:可以在方法之前、之后、發生異常時執行! 實現MethodInterceptor接口
最終通知:不論目標方法是否發生異常都會執行
切點和切面:切點是:在目標方法之前這個點、目標方法之后這個點、在目標方法發生異常這個點
切面是:在切點執行的代碼塊。
環繞通知:
可以獲取目標方法的 完全控制權!(方法是否執行、控制參數、控制返回值)
在使用環繞通知時,目標方法的一切信息,都可以通過invocation(invoke方法傳進去的參數名稱)參數獲取到
public class SurroundMethod implements MethodInterceptor{ public Object invoke(MethodInvocation invocation) { Object result = null; try { System.out.println("環繞通知里面的【前置通知】。。。"); result = invocation.proceed(); //這里相當於執行目標方法 如果不寫目標方法就不會執行 // result是目標方法的返回值 System.out.println("環繞通知里面的【后置通知】..."); } catch (Throwable e) { System.out.println("這里是執行環繞通知里面的【異常通知】。。。"); e.printStackTrace(); } finally{ System.out.println("這里是執行環繞通知里面的【最終通知】"); } return result; //也可以返回其他 return “123”; 那么目標方法的返回值就是 "123" } }
在applicationContext.xml文件中的配置 然后執行目標方法
<bean></bean> 通知類要寫進來 <aop:config> <!-- 切點 --> <aop:pointcut expression="execution(【這里是目標方法的具體信息】public * com.service.AddStudent.addStudent())" id="addStudent1"/> <!-- 連線 切點和切面連接起來 --> <aop:advisor advice-ref="interceptMethod" pointcut-ref="addStudent1"/> </aop:config>