自定義注解與AOP(面向切面編程)的結合常常用于在應用程序中劃定切面,以便在特定的方法或類上應用橫切關注點。以下是一個簡單的示例,演示了如何創建自定義注解,并使用Spring AOP來在被注解的方法上應用通知。
如何創建自定義注解
鏈接
創建注解
首先,創建一個自定義注解:
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 "";
}
這個注解名為 MyCustomAnnotation,它可以標注在方法上,具有一個可選的字符串值。
創建切面
然后,創建一個切面類,定義通知,并使用切入點表達式匹配被 MyCustomAnnotation 注解標注的方法:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;@Aspect
@Component
public class MyAspect {@Before("@annotation(myCustomAnnotation)")public void beforeAdvice(MyCustomAnnotation myCustomAnnotation) {String value = myCustomAnnotation.value();System.out.println("Before method execution with custom annotation. Value: " + value);}
}
這個切面類使用了 @Before 注解,它的參數是一個切入點表達式 @annotation(myCustomAnnotation),表示在被 MyCustomAnnotation 注解標注的方法執行前執行。方法的參數 MyCustomAnnotation myCustomAnnotation 允許你獲取到注解上的值。
最后,在你的服務類中使用 MyCustomAnnotation 注解:
import org.springframework.stereotype.Service;@Service
public class MyService {@MyCustomAnnotation(value = "Custom Value")public void myMethod() {System.out.println("Executing myMethod");}
}
在這個例子中,MyService 類中的 myMethod 方法上標注了 MyCustomAnnotation 注解。當調用這個方法時,切面中的通知會在方法執行前輸出相關信息。
這樣,你就通過自定義注解和AOP結合的方式,實現了在特定方法上應用通知的需求。
使用切入點
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;@Aspect
@Component
public class MyAspect {// 定義切入點,匹配所有使用 @MyCustomAnnotation 注解的方法@Pointcut("@annotation(com.example.demo.MyCustomAnnotation)")public void myCustomAnnotationPointcut() {}// 在切入點之前執行通知@Before("myCustomAnnotationPointcut()")public void beforeAdvice() {System.out.println("Before method execution with custom annotation");}
}