1.主要注解
注解 | 说明 |
---|
@Before | 在目标类的方法执行之前执行 |
@After | 在目标类的方法执行之后执行,如果程序出现了异常,最终通知也会执行。 |
@AfterReturning | 方法正常执行后的通知 |
@AfterThrowing | 在抛出异常后通知 |
@Around | 方法的执行前后执行 |
2.切面类的参考模板
package com.zslaa.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class MyAspect {
@Before(value = "execution(public * com.zslaa.service.impl.UserServiceImpl.*(..))")
public void before() {
System.out.println("前置通知");
}
@After(value = "execution(public * com.zslaa.service.impl.UserServiceImpl.*(..))")
public void after() {
System.out.println("最终通知");
}
@AfterReturning(value = "execution(public * com.zslaa.service.impl.UserServiceImpl.*(..))")
public void afterReturning() {
System.out.println("后置通知");
}
@AfterThrowing(value = "execution(public * com.zslaa.service.impl.UserServiceImpl.*(..))")
public void afterThrowing() {
System.out.println("异常通知");
}
@Around(value = "execution(public * com.zslaa.service.impl.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint pjp) {
System.out.println("前置通知--前面代码");
try {
pjp.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("前置通知--后面代码");
}
}