Springboot学习09:AOP
Posted 我不吃番茄
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot学习09:AOP相关的知识,希望对你有一定的参考价值。
Springboot学习09:AOP
基础概念图
源码示例
切点
import org.springframework.web.bind.annotation.*; @RestController public class AopController { @GetMapping("/beforeAop") @AopBeforeAnno public String beforeAop(){ System.out.println("beforeAop controller...."); return "Success"; } @GetMapping("/afterAop") @AopAfterAnno public String afterAop(){ System.out.println("afterAop controller...."); return "Success"; } @PostMapping("/aroundAop/{id}") @AopAroundAnno public String aroundAop( @PathVariable Long id, @RequestParam String code, @RequestBody AroundAopReq aroundAopReq){ System.out.println("aroundAop controller...."); return "Success"; } }
切面
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; import java.util.Arrays; @Component @Aspect public class AopHandler { //1-前置通知 //@Pointcut("execution(* com.example.bigdemo.aop.AopController.*(..))") @Pointcut("@annotation(com.example.bigdemo.aop.AopBeforeAnno)") public Object beforePointCut(){ return null; } @Before(value="beforePointCut()") public Object before(){ System.out.println("start aop before task here..."); return null; } //后置通知 @Pointcut("@annotation(com.example.bigdemo.aop.AopAfterAnno)") public Object afterPointCut(){ return null; } @After("afterPointCut()") public Object after(){ System.out.println("start aop After task here..."); return null; } //环绕通知 @Pointcut("@annotation(com.example.bigdemo.aop.AopAroundAnno)") public Object aroundPointCut(){ return null; } @Around("aroundPointCut()") public Object around( ProceedingJoinPoint proceedingJoinPoint){ System.out.println("start aop around task here..."); try { System.out.println(Arrays.stream(proceedingJoinPoint.getArgs())); Arrays.stream(proceedingJoinPoint.getArgs()).forEach(args->{ System.out.println(args); }); System.out.println(proceedingJoinPoint.getKind()); System.out.println(proceedingJoinPoint.getSignature()); System.out.println(proceedingJoinPoint.getTarget()); System.out.println(proceedingJoinPoint.getThis()); proceedingJoinPoint.proceed(); } catch (Throwable throwable) { throwable.printStackTrace(); } System.out.println("end aop around task here..."); return null; } }
自定义注解和POJO
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface AopAfterAnno { } @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface AopAroundAnno { } @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface AopBeforeAnno { } public class AroundAopReq { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
END
以上是关于Springboot学习09:AOP的主要内容,如果未能解决你的问题,请参考以下文章