spring AOP pointcut 詳細用法

1.首先這是我幾天來對切面的編程的理解,之前有稍微學了下 spring切面的編程,spring中事物處理常常與pointcut相結合。

pointcut的註解類型 表達式 我就不多說了 。具體可以看spring文檔的第199頁~200頁,都比較簡單。


大體上是這樣的 註解 + (表達標籤+表達式格式)

如: @Pointcut (value="execution(* com.cn.spring.aspectj.NotVeryUsefulAspectService.*(..))")

       @ 註解( value=“ 表達標籤 ( 表達式格式)”)

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;


@Aspect
@Component
public class NotVeryUsefulAspect {
@AfterReturning(value="execution(* com.cn.spring.aspectj.NotVeryUsefulAspectService.*(..))")
private void logReceiver(){
System.out.println("切入點logReceiver...");
}

@Pointcut(value="execution(* com.cn.spring.aspectj.NotVeryUsefulAspectService.*(..)) && args(param)")
private void pointcut(String param){ 
System.out.println("切入點pointcut()"+param);
}

//方法體將不執行
@Pointcut("within(com.cn.spring.aspectj.*)")
public String inWebLayer() {
System.out.println("切入點inWebLayer()");
return "返回值加載";
}

@Before(value="inWebLayer()")
private void beforeinWebLayer(){ 
System.out.println("beforeinWebLayer~~");
}

@Before(value="pointcut(param)")
private void beforePointcut(String param){ 
System.out.println("beforePointcut:"+param);
}


@AfterReturning(pointcut="inWebLayer()",returning="retVal")
public void doAccessCheck(Object retVal) {
System.out.println("doAccessCheck:"+retVal);
}

@Around(value="execution(* com.cn.spring.aspectj.NotVeryUsefulAspectService.*(..))")
private Object aroundLayer(ProceedingJoinPoint pjp) throws Throwable{ 
// start stopwatch
Object retVal = pjp.proceed();
// stop stopwatch
System.out.println("aroundLayer~~");
return retVal;
}
}

以上聲明需要注意:spring基本包不提供Aspect包,需要另外引入,可以去eclipse官網下載:http://www.eclipse.org/aspectj/

注意 申明@Aspect 需要 引入該bean  否則 spring將不識別。如上@Component或者xml引入

表達式中攔截了com.cn.spring.aspectj.NotVeryUsefulAspectService該類中所有方法。當執行行該類中方法時 執行相應的攔截方法,pointcut只負責 切入方法,並未執行方法體。這點要注意!

此後 講解下Aspect  幾個通知註解(advice) 

@Pointcut 攔截的切入點方法,註解的在方法級別之上,但是不執行方法體,只表示切入點的入口。

@Before 顧名思義 是在 切入點 之前執行 方法。

@AfterReturning 返回攔截方法的返回值 

@AfterThrowing 攔截的方法 如果拋出異常 加執行此方法 throwing="ex" 將異常返回到參數列表

@After 在之上方法執行後執行結束操作


@Around  判斷是否執行 以上的攔截 ,第一個參數必須ProceedingJoinPoint. 如要攔截: 


@Around(value="execution(* com.cn.spring.aspectj.NotVeryUsefulAspectService.*(..))")
private Object aroundLayer(ProceedingJoinPoint pjp) throws Throwable{ 
// start stopwatch
Object retVal = pjp.proceed();
// stop stopwatch
System.out.println("aroundLayer~~");
return retVal;
}

就代表 需要執行之後的攔截 ,此攔截 在@Before 之前 做邏輯判斷。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章