睁眼写BUG,闭眼改BUG。

Spring Boot (6) AOP

2019.06.25

AOP(面向切面编程), 用途: 在系统运行过程中动态添加代码.

Spring Boot AOP

  1. 引入依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
  1. 新建 UserService
/**
 * 业务逻辑
 *
 * @Auther: MaWenyi
 * @Date: 2019/6/25
 * @Description: com.iscolt.aop.service
 * @version: 1.0
 */
@Service
public class UserService {

    public String getUserById(Long id) {
        System.out.println("get user by id");
        return "user";
    }

    public void deleteUserById(Long id) {
        System.out.println("delete user by id");
    }
}

  1. 新建切面
/**
 * 切面
 *
 * @Auther: MaWenyi
 * @Date: 2019/6/25
 * @Description: com.iscolt.aop.aspect
 * @version: 1.0
 */
@Component
@Aspect
public class LogAspect {

    @Pointcut("execution(* com.iscolt.aop.service.*.*(..))")
    public void pc1() {
    }

    @Before(value = "pc1()")
    public void before(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        System.out.println(name + "开始执行");
    }

    @After(value = "pc1()")
    public void after(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        System.out.println(name + "结束执行");
    }

    @AfterReturning(value = "pc1()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        String name = joinPoint.getSignature().getName();
        System.out.println(name + "返回" + result);
    }

    @AfterThrowing(value = "pc1()", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Exception e) {
        String name = joinPoint.getSignature().getName();
        System.out.println(name + "抛出异常" + e.getMessage());
    }

    @Around("pc1()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        return proceedingJoinPoint.proceed();
    }
}

  1. 新建控制器
/**
 * 控制器
 *
 * @Auther: MaWenyi
 * @Date: 2019/6/25
 * @Description: com.iscolt.aop.web.controller
 * @version: 1.0
 */
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/getUserById")
    public String getUserById(Long id) {
        return userService.getUserById(id);
    }

    @GetMapping("/deleteUserById")
    public void deleteUserById(Long id) {
        userService.deleteUserById(id);
    }
}