spring boot如何自定義註解

總共分三步:

1、創建一個註解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
@Target(ElementType.METHOD) // 註解的目標爲方法
@Retention(RetentionPolicy.RUNTIME) // 註解在運行時保留,可通過反射訪問
public @interface MyCustomAnnotation {
    String value() default ""; // 定義一個屬性
}

2、創建一個使用註解的類

import org.springframework.stereotype.Service;
 
@Service
public class MyService {
 
    @MyCustomAnnotation("someValue")
    public void myMethod() {
        // 方法實現
    }
}

3、註解處理

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
 
@Aspect
@Component
public class MyCustomAnnotationAspect {
 
    @Pointcut("@annotation(MyCustomAnnotation)")
    public void myCustomAnnotationPointcut() {
    }
 
    @Around("myCustomAnnotationPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 在目標方法執行前執行的邏輯
        System.out.println("Before method execution");
        
        Object result = joinPoint.proceed(); // 執行目標方法
        
        // 在目標方法執行後執行的邏輯
        System.out.println("After method execution");
        
        return result;
    }
}

 

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