标签:调用接口 插入 运算 规则 dad 表示 rest 执行顺序 用户
1 // MainController.java 2 @RestController 3 public class MainController { 4 RequestMapping(value="/doSomething", method = RequestMethod.POST) 5 @CrossOrigin("*") 6 public void doSomething() { 7 System.out.println("This is doSomething"); 8 test(); 9 } 10 11 @RequestMapping(value="/justTest", method = RequestMethod.POST) 12 @CrossOrigin("*") 13 public void test() { System.out.println("This is test");} 14 }
ExampleAop.java为AOP相关代码,定义了pointcut和多个Advice函数。
1 // ExampleAop.java 2 @Component 3 @Aspect 4 @Order(1) 5 public class ExampleAop { 6 7 private static final Logger LOGGER = LoggerFactory.getLogger(ExampleAop.class); 8 9 // 匹配com.example.demo包及其子包下的所有类的所有方法 10 @Pointcut("execution(* com.example.demo..*.*(..))") 11 public void executeService() { 12 } 13 14 @Before("executeService()") 15 public void doBeforeAdvice(JoinPoint joinPoint) throws Exception { 16 LOGGER.info("Before [{}]", joinPoint.getSignature().getName()); 17 } 18 19 @Around("executeService()") 20 public void doAroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable { 21 LOGGER.info("Around1 [{}]", joinPoint.getSignature().getName()); 22 joinPoint.proceed(); 23 LOGGER.info("Around2 [{}]", joinPoint.getSignature().getName()); 24 } 25 26 @After("executeService()") 27 public void doAfterAdvice(JoinPoint joinPoint) throws Exception { 28 LOGGER.info("After [{}]", joinPoint.getSignature().getName()); 29 } 30 31 @AfterReturning("executeService()") 32 public void doAfterReturningAdvice(JoinPoint joinPoint) throws Exception { 33 LOGGER.info("AfterReturning [{}]", joinPoint.getSignature().getName()); 34 } 35 }
编译并运行jar包,调用接口/doSomething。
1 # 调用接口 2 curl localhost:8080/doSomething
到服务器观察日志。
1 <!-- 后台日志 --> 2 com.example.demo.aop.ExampleAop : Around1 [doSomething] 3 com.example.demo.aop.ExampleAop : Before [doSomething] 4 This is doSomething 5 This is test 6 com.example.demo.aop.ExampleAop : Around2 [doSomething] 7 com.example.demo.aop.ExampleAop : After [doSomething] 8 com.example.demo.aop.ExampleAop : AfterReturning [doSomething]
1 execution(public * com.example.demo.ExampleClass.*(..)) // ExampleClass的所有公有方法 2 execution(* com.example.demo..*.*(..)) // com.example.demo包及其子包下的所有方法 3 logSender() || logMessage() // 两个签名的表达式的并集
(一个猜测)
Spring入门之AOP实践:@Aspect + @Pointcut + @Before / @Around / @After
标签:调用接口 插入 运算 规则 dad 表示 rest 执行顺序 用户
原文地址:https://www.cnblogs.com/desertfish/p/11421260.html