1. 程式人生 > 其它 >SpringBoot自定義註解結合AOP輸出方法呼叫日誌

SpringBoot自定義註解結合AOP輸出方法呼叫日誌

技術標籤:Javajavaspring bootaop

必要的依賴包

在pom.xml中新增如下依賴:

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<
artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok<
/groupId> <artifactId>lombok</artifactId> </dependency>

輸入日誌註解

這裡定義一個實現日誌輸出的註解:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLogAnnotation {
}

定義切面類

定義一個切面類用於匹配自定義的註解:

@Configuration
@Aspect
@Slf4j
public class MyLogAnnotationAopConfig
{ //通過@within和@annotation保證註解使用在類和方法上都能正常工作 @Around(value = "@within(com.example.aop.annotation.MyLogAnnotation)||@annotation(com.example.aop.annotation.MyLogAnnotation)") public void doAround(ProceedingJoinPoint joinPoint) { String methodName = joinPoint.getSignature().getName(); //方法執行之前 log.info("準備執行 " + methodName + " 方法"); try { //執行方法 joinPoint.proceed(); } catch (Throwable throwable) { throwable.printStackTrace(); } //方法執行之後 log.info(methodName + " 方法已執行完畢"); } }

定義控制層

此處定義一個控制層對外提供API介面呼叫:

@RestController
@RequestMapping("/")
@Slf4j
@MyLogAnnotation        //在型別上使用自定義註解
public class AopController {
    @GetMapping("/test1")
    public void test1() {
        log.info("執行 test1 方法");
    }

    @GetMapping("/test2")
    public void test2() {
        log.info("執行 test2 方法");
    }
}

測試結果

在瀏覽器分別輸入http://localhost:8100/test1和http://localhost:8100/test2檢視日誌輸出結果:
在這裡插入圖片描述
在這裡插入圖片描述