0、切點:
0.1:方法切點:
@Pointcut(value="execution(* cn.xxx.ssm.ssmtemplate.service.*.*(..))")
private void addLog1() {}
@Pointcut(value="execution(* cn.xxx.ssm.ssmtemplate.service.*.*(..))&&args(arg0,arg1)",argNames="arg0,arg1")
private void addLog2(String arg0,String arg1) {}
0.2:註解切點:
@Pointcut("@within(org.springframework.stereotype.Controller)")
private void exceptionProcesser() {}
注:註解切點可以有@target和@within,區別如下:
對象的運行時綁定的方法所屬的類必須與被@within或@target中的註解類型所註解的類是同一個類,方法攔截才生效。
運行時綁定的方法是指運行時對象動態綁定的方法,一般指override方法。
- @target要求對象的運行時類型與被註解的類型是同一個類型
- @within要求對象的運行時類型是被註解的類型的子類
1、前置通知:
@Before(value = "addLog()")
public void beforeMethod(JoinPoint jp) {
String methodName = jp.getSignature().getName();
System.out.println("【前置通知】the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs()));
}
@Before(value = "addLog(a,b)",argNames="a,b")
public void beforeMethod(JoinPoint jp,String a,String b) {
String methodName = jp.getSignature().getName();
System.out.println("【前置通知】the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs()));
}
2、後置通知
@After(value="addLog()")
public void afterMethod(JoinPoint jp) {
System.out.println("【後置通知】this is a afterMethod advice...");
}
3、返回通知
@AfterReturning(value = "addLog()", returning="result")
public void afterReturningMethod(JoinPoint jp, Object result) {
String methodName = jp.getSignature().getName();
System.out.println("【返回通知】the method 【" + methodName + "】 ends with 【" + result + "】");
}
@AfterReturning(value = "addLog(a,b)", argNames="a,b,result", returning="result")
public void afterReturningMethod(JoinPoint jp, String a, String b,Object result) {
String methodName = jp.getSignature().getName();
System.out.println("【返回通知】the method 【" + methodName + "】 ends with 【" + result + "】");
}
4、異常通知
@AfterThrowing(value = "addLog()", throwing = "e")
public void afterThorwingMethod(JoinPoint jp, RuntimeException e) {
String methodName = jp.getSignature().getName();
System.out.println("【異常通知】the method 【" + methodName + "】 occurs exception: " + e);
}
@AfterThrowing(value = "addLog(a,b)", argNames="a,b,e", throwing = "e")
public void afterThorwingMethod(JoinPoint jp, String a, String b, RuntimeException e) {
String methodName = jp.getSignature().getName();
System.out.println(a);
System.out.println(b);
System.out.println("【異常通知】the method 【" + methodName + "】 occurs exception: " + e);
}
5、環繞通知
@Around(value="exceptionProcesser()")
public Object around(ProceedingJoinPoint jp) throws Throwable {
String methodName = jp.getSignature().getName();
System.out.println("【環繞通知】the method 【" + methodName + "】 around run");
return null;
}