總共分三步:
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; } }