今天说一说Spring AOP吧。
AOP是一种思想,Spring只是支持AOP的一种框架,而不是AOP属于Spring。
1 AOP能干什么?
- 举一个AOP的例子方便理解,现在有一个需求,让我们手写一个Spring Boot的拦截器,用来校验前台发送过来的请求。
首先来个一比较low B的实现,在需要拦截每个Controller请求的方法体中都校验一下前台发送过来的验证信息(token等),就想验证参数一样,非法请求直接驳回。
但是这样一个问题,我们需要些许多的重复代码。那么这个代码就进化了,把重复的代码提炼成一个方法,需要使用的地方直接调用,简洁了不少。
但是还是需要调用呀,还是很麻烦,忘记调用了怎么办?这是我们就可以采用AOP的思想来解决问题了,他完全可以在不修改源码的情况下,为系统中的增加一些通用功能。 - 所谓面向切面编程实际上就是将程序抽象成我们所需要关注的切面,结合上面的例子,我们可以简单的切面理解成请求到Controller前面的那一层控制。
2 初识Spring AOP
2.1 AOP术语
在了解Spring AOP之前,先要了解一下AOP通用术语:
- 增强:对现有代码的功能扩展,也就是上述例子中的拦截器功能;
- 通知(Advice): AOP 框架中的增强处理。通知描述了切面何时执行以及如何执行增强处理。
- 连接点(join point): 连接点表示应用执行过程中能够插入切面的一个点,这个点可以是方法的调用、异常的抛出。在 Spring AOP 中,连接点总是方法的调用。
- 切点(PointCut): 可以插入增强处理的连接点。
- 切面(Aspect): 切面是通知和切点的结合。
- 引入(Introduction):引入允许我们向现有的类添加新的方法或者属性。
- 织入(Weaving): 将增强处理添加到目标对象中,并创建一个被增强的对象,这个过程就是织入。
这些个玩意吧,只可意会不可言传,使用中自己慢慢理解吧。
2.2 来看一个简单的代码实例
- 新建一个Spring Boot项目
引入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
@RestController
@RequestMapping("graph")
public class GraphController {
@Autowired
@Qualifier("circular")
private IGraphService graphServiceCircular;
@Autowired
@Qualifier("rectangle")
private IGraphService graphServiceRectangle;
@GetMapping("getArea")
public float getArea() {
return this.graphServiceCircular.getArea() + this.graphServiceRectangle.getArea();
}
}
public interface IGraphService {
float getArea();
}
import com.spheign.szjx.service.IGraphService;
import org.springframework.stereotype.Service;
@Service(value = "circular")
public class CircularImpl implements IGraphService {
@Override
public float getArea() {
System.out.println("计算圆的面积");
return 100;
}
}
import com.spheign.szjx.service.IGraphService;
import org.springframework.stereotype.Service;
@Service("rectangle")
public class RectangleImpl implements IGraphService {
@Override
public float getArea() {
System.out.println("计算矩形的面积");
return 200;
}
}
很明显,这时候访问http://localhost:8080/graph/getArea
得到的输出是
计算圆的面积
计算矩形的面积
- 这时候我要添加一个切面
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class GraphAspect {
@Before("execution(* com.spheign.szjx.service.IGraphService.getArea(..))")
public void begin(){
System.out.println("Before 开始计算");
}
@After("execution(* com.spheign.szjx.service.IGraphService.getArea(..)) && bean(circular)")
public void end(){
System.out.println("After 计算结束");
}
@AfterReturning("execution(* com.spheign.szjx.service.IGraphService.getArea(..))")
public void returnEnd(){
System.out.println("返回结束");
}
@Around("execution(* com.spheign.szjx.service.IGraphService.getArea(..))")
public Object inTo(ProceedingJoinPoint joinPoint){
Object obj = null;
System.out.println("Around 开始");
try {
obj = joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
System.out.println("Around 结束");
return obj;
}
}
此时程序的输出为
Around 开始
Before 开始计算
计算圆的面积
返回结束
After 计算结束
Around 结束
Around 开始
Before 开始计算
计算矩形的面积
返回结束
Around 结束
上述代码就是阐述了AOP的优势,几乎是完全无侵入式的修改了代码。
2.3 理解代码含义
- 首先是Spring AOP所支持的AspectJ切点指示器
项目类型 | 描述 |
---|---|
arg() | 限定连接点方法参数 |
@args() | 通过连接点方法参数上的注解进行限定 |
execution() | 用于匹配是连接点的执行方法 |
this() | 限制连接点匹配AOP代理Bean引用为指定的类型 |
target | 目标对象(即被代理对象) |
@target() | 限制目标对象的配置了指定的注解 |
within | 限制连接点匹配执行的类型 |
@within() | 限定连接点带有匹配注解类型 |
@annotation | 限定带有指定注解的连接点 |
上述实例中我们采用的是execution()指示器来来标识连接点,还有一个bean
我们也是用到了,但他是Spring特有的指示器。
- 切点表达式
我们先拿execution()举例
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern?name-pattern(param-pattern) throws-pattern?)
这里问号表示当前项可以有也可以没有,其中各项的语义如下:
- modifiers-pattern:方法的可见性,如public,protected;
- ret-type-pattern:方法的返回值类型,如int,void等;
- declaring-type-pattern:方法所在类的全路径名,如com.spring.Aspect;
- name-pattern:方法名类型,如buisinessService();
- param-pattern:方法的参数类型,如java.lang.String;
- throws-pattern:方法抛出的异常类型,如java.lang.Exception;
再来解释两个通配符
* 模糊匹配任意结果,可以是前缀也可以是后缀或全匹配;
.. 表示0个或多个项目,如果用于declaring-type-pattern中,则表示匹配当前包及其子包,如果用于param-pattern中,则表示匹配0个或多个参数。
举个例子就明白了了
execution(* com.aaa.bbb..*.ccc*(..))
上述切点表达式表示在com.aaa.bbb包及子包下任意类中方法名以ccc开头方法且参数个数任意,返回值也任意的方法。
- 使用注解声明出的的5中通知类型
@Before
:在目标方法调用前执行;
@After
:在目标方法调用后执行;
@AfterReturning
:在目标方法调用前执行;
@AfterThrowing
:在目标方法调用前执行;
@Around
:在目标方法调用前执行。
现在再去看上面例子的输出就明白了这些通知类型的作用时机,值得注意的是 @Around
修饰的环绕通知类型并且需要调用 ProceedingJoinPoint
的 proceed()
方法,否则原目标方法将被阻塞,无法继续执行。
2.4 带参数的情况
如果切点需要对目标方法中的参数进行判断或处理该怎么办呢?
现在我们给方法中加一个参数r:
@GetMapping("getArea")
public float getArea() {
return this.graphServiceCircular.getArea(10) + this.graphServiceRectangle.getArea(20);
}
import com.spheign.szjx.service.IGraphService;
import org.springframework.stereotype.Service;
@Service(value = "circular")
public class CircularImpl implements IGraphService {
@Override
public float getArea(float r) {
System.out.println("计算圆的面积");
return (3.14f * r);
}
}
import com.spheign.szjx.service.IGraphService;
import org.springframework.stereotype.Service;
@Service("rectangle")
public class RectangleImpl implements IGraphService {
@Override
public float getArea(float r) {
System.out.println("计算矩形的面积");
return r * r;
}
}
为了查看方便,我们只保留@Around
这一种通知类型,并且使用arg()
指示器来获取连接点的方法参数。
@Around("execution(* com.spheign.szjx.service.IGraphService.getArea(..)) && args(r)")
public Object inTo(ProceedingJoinPoint joinPoint, float r){
Object obj = null;
System.out.println("Around 开始" + r);
try {
obj = joinPoint.proceed();
if(r > 10){
System.out.println("超出我的计算能力了");
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
System.out.println("Around 结束" + r);
return obj;
}
再来看执行结果:
Around 开始10.0
计算圆的面积
Around 结束10.0
Around 开始20.0
计算矩形的面积
超出我的计算能力了
Around 结束20.0
大概就是这么个意思。