面向方面编程(AOP)通过提供另一种思考程序结构的方式来补充面向对象编程(OOP)。
OOP中模块化的关键单元是类,而在AOP中,模块化单元是方面。
先来介绍一下
@Aspect @Pointcut @Around @Before @After @AfterReturning @AfterThrowing
@Aspect:类定义为切面类,指定为切面
@Pointcut: 切入点,等很多写法,也可以直接作用在某些包下
注意:private修饰的无法拦截
@Around:环绕通知,其包含了前置和后置通知,proceed方法就是用于启动目标方法执行的,proceed是必须执行的
@Before:前置通知 在切入点之前执行
@After:后置通知,在切入点之后执行
@AfterReturning:后置通知处理(我自己私下叫的,方便记忆,意思大概就这么个意思),方法正常退出时执行
@AfterThrowing: 后置异常处理(我自己私下叫的,方便记忆,意思大概就这么个意思),这个是在切入执行异常报错的时候执行的
好了先上菜
package com.example.demo.aspact;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Aspect
@Component
public class AopAspect {
@Pointcut("execution(public * com.example.demo.controller..*.*(..))")
public void pointCut() {
}
@Around(value = "pointCut()")
public Object Around(ProceedingJoinPoint pjp) throws Throwable {
long beginTime = System.currentTimeMillis();
System.out.println("Around:方法环绕开始.....");
Object o = pjp.proceed(); //当使用环绕通知时,proceed方法必须调用,否则拦截到的方法就不会再执行了
long time = System.currentTimeMillis() - beginTime;
sysLog(pjp, time);
System.out.println("Around:方法环绕结束,结果是 :" + o);
return o;
}
private void sysLog(ProceedingJoinPoint point, long time) {
System.out.println("Around:" + "1111");
}
@Before("pointCut()")
public void testBefor() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
System.out.println("Before:" + request.getParameterMap());
}
@After("pointCut()")
public void testAfter() {
System.out.println("After:" + "23333");
}
@AfterReturning(returning = "ret", pointcut = "pointCut()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
System.out.println("AfterReturning: " + ret);
}
// 声明错误e时指定的抛错类型法必会抛出指定类型的异常
// 此处将e的类型声明为Throwable,对抛出的异常不加限制
@AfterThrowing(throwing = "e", pointcut = "pointCut()")
public void doAfterReturning(Throwable e) {
System.out.println("呼叫总部,我们已经偏离了预计轨迹,请求指示");
System.out.println("错误信息" + e.getMessage());
}
}
我这边是接着上一章的demo来写的 https://blog.csdn.net/qq_14926283/article/details/103088572
就是加了一个切面类在这个位置
需要引用到以下包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
好了直接来测试一下postman
还是那上次的接口来测试