springboot(18)- 整合web開發(10)- 整合 AOP

1 整合 AOP

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
  • Service
@Service
public class UserService {

    public String getUsernameById(Integer id){
        System.out.println("getUsernameById");
        return "夏侯惇";
    }

    public void deleteUserById(Integer id){
        System.out.println("deleteUserById");
    }
}

  • Controller
package com.tzb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/test1")
    public String getUsernameById(Integer id){
        return userService.getUsernameById(id);
    }

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

}


  • 日誌組件
@Component
@Aspect
public class LogComponent {

    @Pointcut("execution(* com.tzb.service.*.*(..))")
    public void pc1() {

    }

    @Before(value = "pc1()")
    public void before(JoinPoint jp) {
        String name = jp.getSignature().getName();
        System.out.println("before >>> " + name);
    }

    @After(value = "pc1()")
    public void after(JoinPoint jp) {
        String name = jp.getSignature().getName();
        System.out.println("after >>> " + name);
    }

    // 返回值通知
    @AfterReturning(value = "pc1()", returning = "result")
    public void afterReturning(JoinPoint jp, Object result) {
        String name = jp.getSignature().getName();
        System.out.println("afterReturning >>> " + name + "----" + result);
    }

    // 異常通知
    @AfterThrowing(value = "pc1()", throwing = "e")
    public void afterThrowing(JoinPoint jp, Exception e) {
        String name = jp.getSignature().getName();
        System.out.println("afterThrowing >>> " + name);
    }

    // 環繞通知
    @Around(value = "pc1()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object proceed = pjp.proceed();
        return proceed;
    }

}


在這裏插入圖片描述
在這裏插入圖片描述


在這裏插入圖片描述
在這裏插入圖片描述


  • 修改環繞通知返回值
    在這裏插入圖片描述

在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章