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;
}