面向切面 (AOP)aspect oriented programming

将通用逻辑从业务逻辑中分离出来

  1. 创建 ```java package com.example.luckymoney.aspect;

import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component;

@Aspect @Component public class HttpAspect {

  1. @Before("execution(public * com.example.luckymoney.controller.LuckymoneyController.*(..))")
  2. public void logBefore() {
  3. System.out.println("11111");
  4. }
  5. @After("execution(public * com.example.luckymoney.controller.LuckymoneyController.*(..))")
  6. public void logAfter() {
  7. System.out.println("22222");
  8. }

}

  1. 2. 改进
  2. ```java
  3. package com.example.luckymoney.aspect;
  4. import org.aspectj.lang.annotation.After;
  5. import org.aspectj.lang.annotation.Aspect;
  6. import org.aspectj.lang.annotation.Before;
  7. import org.aspectj.lang.annotation.Pointcut;
  8. import org.springframework.stereotype.Component;
  9. @Aspect
  10. @Component
  11. public class HttpAspect {
  12. @Pointcut("execution(public * com.example.luckymoney.controller.LuckymoneyController.*(..))")
  13. public void log() {
  14. }
  15. @Before("log()")
  16. public void logBefore() {
  17. System.out.println("11111");
  18. }
  19. @After("log()")
  20. public void logAfter() {
  21. System.out.println("22222");
  22. }
  23. }