域名解析网站登录,云服务器怎么做网站,建设包银行官方网站,寮步网页设计Spring Boot Aop 执行顺序
1. 概述
在 spring boot 项目中#xff0c;使用 aop 增强#xff0c;不仅可以很优雅地扩展功能#xff0c;还可以让一写多用#xff0c;避免写重复代码#xff0c;例如#xff1a;记录接口耗时#xff0c;记录接口日志#xff0c;接口权限使用 aop 增强不仅可以很优雅地扩展功能还可以让一写多用避免写重复代码例如记录接口耗时记录接口日志接口权限等等。所以在项目中学习并使用 aop 是十分必要的。然而当我们在一个接口中使用多个 aop时就需要注意他们的执行顺序了。那么它们的执行顺序是怎样的呢如果不把这个问题搞明白那我们的程序就不可控这是不允许的这就是我们今天要讨论的问题。
2. 实现 AOP
2.1 通过注解实现 AOP
MyAop:
Target({ElementType.METHOD})
Retention(RetentionPolicy.RUNTIME)
public interface MyAop {
}MyAspect:
Aspect
Component
public class MyAspect {Around(annotation(aop))public Object around(ProceedingJoinPoint joinPoint, MyAop aop) throws Throwable {return joinPoint.proceed();}}SampleController#myApi:
RestController
RequestMapping(/sample)
public class SampleController {MyAopRequestMapping(/my-api)public String myApi() {return success;}}这样我们就通过使用注解的方式实现了 AOP 。
2.2 通过扫描包
比如我们有这样一个接口 SampleController#myApi2:
RestController
RequestMapping(/sample)
public class SampleController {RequestMapping(/my-api2)public String myApi2() {return success;}}我们可以使用包扫描的方式进行拦截
Aspect
Component
public class My2Aspect {Around(execution(* com.fengwenyi.demo.springboot.aop.controller.SampleController.myApi2(..)))public Object around(ProceedingJoinPoint joinPoint) throws Throwable {return joinPoint.proceed();}}这样我们也就通过使用包扫描的方式实现了 AOP 。
3. 多个 AOP
3.1 分析
先提一个疑问多个AOP注解执行顺序是怎么样的呢如何设置执行顺序呢
比如APP 请求我们的 API 接口在请求到达 API 接口之前可以先执行 AOP1在执行 AOP2并且顺序不能变如下图 我们再拆解一下实际内部执行逻辑。
请求请求先进入到 AOP1再进入到 AOP2最后到达 API。
返回执行完 API再回到 AOP2最后回到 AOP1。
如下图 因为我们用的是 Around先进入Aop1再进入到aop2然后执行api执行完以后再返回到 aop2最后返回aop1。
3.2 代码实现
MyFirstAop
Target({ElementType.METHOD})
Retention(RetentionPolicy.RUNTIME)
public interface MyFirstAop {
}MyFirstAspect:
Slf4j
Aspect
Component
Order(100002)
public class MyFirstAspect {Around(annotation(aop))public Object around(ProceedingJoinPoint joinPoint, MyFirstAop aop) throws Throwable {log.info(MyFirstAspect#around execute start);try {return joinPoint.proceed();} finally {log.info(MyFirstAspect#around execute end);}}}MySecondAop:
Target({ElementType.METHOD})
Retention(RetentionPolicy.RUNTIME)
public interface MySecondAop {
}MySecondAspect:
Slf4j
Aspect
Component
Order(100003)
public class MySecondAspect {Around(annotation(aop))public Object around(ProceedingJoinPoint joinPoint, MySecondAop aop) throws Throwable {log.info(MySecondAspect#around execute start);try {return joinPoint.proceed();} finally {log.info(MySecondAspect#around execute end);}}}SampleController#aopOrder:
RestController
RequestMapping(/sample)
public class SampleController {MySecondAopMyFirstAopRequestMapping(/aop-order)public String aopOrder() {return aopOrder;}}通过设定 Order 值指定 AOP 执行顺序与我们的期望一致。
好了今天的分享就到这里了源码demo-spring-boot-aop。