
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
3.7 AOP
AOP(Aspect-Oriented Programming,面向切面编程)可以添加额外行为到现有指定条件的一批Bean上,但是我们并不需要修改Bean的代码,这样可对额外行为和Bean本身的行为实现关注隔离。
在学习AOP之前,先来熟悉下面的概念。
◎切面:Aspect,编写额外行为的地方。
◎连接点:Join Point,被拦截的方法。
◎切点:PointCut,通过条件匹配一批连接点。
◎建言:Advice,对于每个连接点需要做的行为。
◎目标对象:符合指定条件的Bean。
在使用AOP开发之前,需要使用@EnableAspectJAutoProxy注解来开启对AspectJ的支持,Spring Boot已经自动做了配置,所以无须额外声明。
下面编写一个使用AOP来记录操作日志的例子。编写一个注解,作为切点拦截条件。

目标对象:

下面是最重要的部分,编写切面部分的代码。

a.使用@Aspect定义一个切面。
b.使用@Pointcut,它会将所有注解了@Logging注解的方法作为条件。
c.使用@Before建言,它使用的切点annotationPointCut()会针对符合切点条件的Bean执行beforeAnnotationPointCut()方法里的行为。
d.joinPoint代表被拦截的方法,可以从joinPoint中获得方法的签名信息。
e.通过joinPoint获得被拦截方法的参数。
f.通过joinPoint获得被拦截方法的注解信息。
g.使用@AfterReturning建言,可以获得被拦截方法的返回值retName。
在JavaConfig中执行下面的代码,结果如图3-17所示。


图3-17