分类:
@Before:前置通知
@After:后置通知
@Around:环绕通知
@AfterReturning:目标方法返回通知
@AfterThrowing:目标方法异常通知
@Aspect
@Component
public class MyAspect {
@Pointcut(value="excution(* com.*.*(..))")
public void pointCut() {
}
@Before(value="pointCut()")
public void before() {
System.out.println("before");
}
@After(value="pointCut()")
public void after() {
System.out.println("after");
}
@AfterReturning(value="pointCut()")
public void afterReturning() {
System.out.println("return");
}
@AfterThrowing(value="pointCut()")
public void afterThrowing() {
}
@Around(value="pointCut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("around before");
Object result = joinPoint.proceed();
System.out.println("around after");
return result;
}
}
正常情况下各方法的执行顺序:
Around(JoinPoint.proceed())之前的部分——>
Before——>需要增强的方法——>Return——>After——>
Around(JoinPoint.proceed())后的部分
抛出异常的情况:
Before,After抛出异常:会阻止before之后的程序运行,AfterThrowing不会被触发。
AfterReturning抛出异常:会阻止Around(JoinPoint.proceed())后的部分。
Around(JoinPoint.proceed())前抛出异常:会阻止同一个目标方法上所有的通知。
Around(JoinPoint.proceed())后抛出异常:会阻止后面执行的方法。
目标方法报错:会触发AfterThrowing,在目标方法之后,After之前,会阻止AfterReturning。
传参:
@Aspect
@Component
public class MyAspect {
@Pointcut(value="excution(* com.*.*(..)) && args(a)")
public void pointCut(Integer a) {
}
@Before(value="pointCut(a)",argNames="a")
public void before(Integer a) {
System.out.println("before");
}
}
这里传入了Integer参数a,同时需要目标方法也有Integer参数a