1. 程式人生 > >spring框架基於註解aop的通知

spring框架基於註解aop的通知

張義勝的學習筆記

                 **之spring框架aop的通知**  

1.spring有兩大基石,即IOC容器和AOP切面
2.Aop切面有5個通知:Before(前置通知),After(後置通知),AfterReturning(方法正常結束後的通知),AfterThrowing(異常通知),Around(環繞通知)
3.每個通知後面必須跟一個方法
4.在進行使用代理時,必須在IOC 容器中加入程式碼,該程式碼作用是在呼叫該物件時動態建立一個代理物件。我們須在切面類中加入@Aspect宣告為一個切面,@Component將該物件加入IOC容器進行管理。
5.以用@order指定切面的優先順序,值越小優先順序越高

                 用法

1.Before:首先Before(“execution(public 方法返回值型別 類路徑名.(,*))”)
。後面的方法中可以帶引數JoinPoint joinpoint連線點,一個方法就是一個連線點,可以
根據引數獲取方法名,以及傳入的引數。
2.After與Before類似
3.AfterReturning,與之前的兩個通知有所不同,在AfterReturning中須指明引數returning,即所呼叫方法的返回值。宣告如下@AfterReturning(value=”execution(* com.zhangyisheng.aop.AtithemeticCalculator.(

,*)))”,returning=”result”)
。在這裡需注意returning的引數result要與後面宣告的方法的引數一樣。
4.AfterThrowing與AfterReturning類似,需把returning改為throwing。
5.Around相當於前面4個通知的合併

                示例

@Component
public class AtithemeticCalculatorIMP implements AtithemeticCalculator{

@Override
public int add(int i, int j) {
    // TODO Auto-generated method stub
    int result=i+j;
    return result;
}
@Override
public int sub(int i, int j) {
    // TODO Auto-generated method stub
    int result=i-j;
    return result;
}

@Override
public int mul(int i, int j) {
    // TODO Auto-generated method stub
    int result=i*j;
    return result;
}

@Override
public int div(int i, int j) {
        int result=i/j;
        return result;
}
@Override
public double as(double i, double j) {

    return i+j;
}

}
/**
* 每個通知後都必須跟一個方法
* 可以用@order指定切面的優先順序,值越小優先順序越高*/
@Aspect
@Component
public class LoggingAspect {
//前置通知:目標方法執行之前執行的程式碼
@Before(“execution(public * com.zhangyisheng.aop.AtithemeticCalculator.(,*))”)
public void beforeMethod(JoinPoint joinpoint)
{
String methodName=joinpoint.getSignature().getName();
Listargs=Arrays.asList(joinpoint.getArgs());
System.out.println(“the method “+methodName+” begin with”+args);
}
//後置通知:目標方法執行之後執行的程式碼
@After(“execution(* com.zhangyisheng.aop.AtithemeticCalculator.(,*)))”)
public void after(JoinPoint joinpoint)
{ String methodName=joinpoint.getSignature().getName();
System.out.println(“the method “+methodName+” end”);
}
@AfterReturning(value=”execution(* com.zhangyisheng.aop.AtithemeticCalculator.(,*)))”,returning=”result”)
public void afterReturning(JoinPoint joinpoint,Object result)
{ //正常結束後執行的程式碼
String methodName=joinpoint.getSignature().getName();
System.out.println(“the method “+methodName+” end width “+result);
}
@AfterThrowing(value=”execution(* com.zhangyisheng.aop.AtithemeticCalculator.(,*)))”,throwing=”e”)
public void afterThrowing(JoinPoint joinpoint,Exception e)
{
//異常時,執行的程式碼,兩個引數e要一致
String methodName=joinpoint.getSignature().getName();
System.out.println(“the method “+methodName+” occus a error is “+e);
}
}