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/。
@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 之前 做邏輯判斷。