Joinpoint(连接点):类里面可以被增强的方法即为连接点。例如,想修改哪个方法的功能,
那么该方法就是一个连接点。
Pointcut(切入点):对 Joinpoint 进行拦截的定义即为切入点。例如,拦截所有以 insert 开始的方法,这个定义即为切入点。
Advice(通知):拦截到 Joinpoint 之后所要做的事情就是通知。例如,上文说到的打印日志监控。通知分为前置通知、后置通知、异常通知、最终通知和环绕通知。
Aspect(切面):Pointcut和Advice 的结合
Target(目标对象):要增强的类称为 Target。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class LogAspect {
@Pointcut("execution(* org.sang.aop.service.*.*(..))")
public void pc1() {
}
@Before(value = "pc1()")
public void before(JoinPoint jp) {
String name = jp.getSignature().getName();
System.out.println(name + "方法开始执行...");
}
@After(value = "pc1()")
public void after(JoinPoint jp) {
String name = jp.getSignature().getName();
System.out.println(name + "方法执行结束...");
}
@AfterReturning(value = "pc1()", returning = "result")
public void afterReturning(JoinPoint jp, Object result) {
String name = jp.getSignature().getName();
System.out.println(name + "方法返回值为:" + result);
}
@AfterThrowing(value = "pc1()",throwing = "e")
public void afterThrowing(JoinPoint jp,Exception e) {
String name = jp.getSignature().getName();
System.out.println(name+"方法抛异常了,异常是:"+e.getMessage());
}
@Around("pc1()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
return pjp.proceed();
}
}
import org.sang.aop.model.User;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public String getUserById(Integer id) {
System.out.println("get...");
return "user";
}
public void deleteUserById(Integer id) {
int i = 1 / 0;
System.out.println("delete...");
}
}