Springboot (六) aop自定義註解開發

java自定義註解開發
項目地址

Springboot (六) aop自定義註解開發

前言: 相信用過Spring的對Aop都不陌生,閒話不多說直接上列子。

1. 導入依賴

首先我們要導入aop的依賴,有了boot開發就是方便。

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

2. 編寫例子

  1. 首先我們的需求是,需要一個日誌註解,在方法上,可以截獲關於方法的信息,並存到DB(數據庫)中。@within 支持切入整個類方法

  2. 日誌註解類

    註解中有一個備註屬性。

    @Inherited
    @Documented
    @Target(ElementType.METHOD,ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface LogAnnotation {
    
        String value() default "默認備註";
    }
    
  3. 編寫我們的切面類

    @Aspect
    @Component
    public class LogAspect {
    
    
        // 切入點
        @Pointcut("@within(com.yu.annotationdemo.annotation.LogAnnotation)||@annotation(com.yu.annotationdemo.annotation.LogAnnotation)")
        public void logAnnotationPointcut() {
        }
    
        // 環繞通知
        @Around("logAnnotationPointcut()")
        public Object myAnnotationAround(ProceedingJoinPoint joinPoint) throws Throwable {
            //獲取目標類名
            String targetName = joinPoint.getTarget().getClass().getName();
            //獲取方法名
            String methodName = joinPoint.getSignature().getName();
            //獲取相關參數
            Object[] arguments = joinPoint.getArgs();
            //生成類對象
            Class targetClass = Class.forName(targetName);
            //獲取該類中的方法
            Method method = targetClass.getMethod(methodName, String.class);
    
            Object proceed = joinPoint.proceed();
    
            System.out.println("方法結束後");
    
            LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
    
            if (logAnnotation != null) {
                String logAnnotationValue = logAnnotation.value();
                // todo 將需要的日誌信息 插入db中
            }
            return proceed;
        }
    }
    
  4. ** 編寫目標方法**

    @RestController
    @RequestMapping("log")
    public class LogServiceImpl {
    
        @LogAnnotation("查詢用戶id")
        @RequestMapping("getUserId")
        public String getUserId(String id){
    
            return id;
        }
    }
    
  5. 運行boot的啓動類。訪問目標URL查看結果。
    在這裏插入圖片描述
    我們簡單的入門例子就結束了,很簡單的代碼。
    附上其他的幾鍾通知類型:
    在這裏插入圖片描述

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