springboot + kotlin使用自定義註解實現aop的切點

一般來說,我們都是這樣定義切點的

 //表示controller包下的任意返回任意個參數的公共方法
@Pointcut("execution(public * org.zhd.crm.server.controller..*.*(..))") 

但是,如果我想要更加靈活,顆粒度更小時,可以使用自定義註解的方式來定義切點。

1.自定義註解
kotlin和java中的寫法還是有點區別的,以下表示保留至運行時用於方法的註解:
kotlin:

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class AnnotationTest(val value: String = "")

java:

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationTest {
    String value() default "";
}

2.aop類(kotlin)

@Aspect
@Service
class WebAopService {
	...
	@Pointcut("@annotation(org.zhd.crm.server.util.AnnotationTest)")
    fun testPoint(){
    }

    @Before("testPoint()")
    fun test1(joinPoint: JoinPoint){
        println(">>>${joinPoint.signature},${joinPoint.target.javaClass.name}")  //返回方法簽名和目標對象的類名
    }

    @Before("testPoint() && @annotation(test)") //@annotation(test)獲取註解對象
    fun test2(joinPoint: JoinPoint, test: AnnotationTest){
        println(">>>${test.value}") //註解的value值
    }
    ...
}

3.在你想要的方法上增加註解(kotlin)

	@AnnotationTest("testAnt")
    @GetMapping("testAop")
    fun testAopAndAnt(): String {
        return "success"
    }

4.結果
在這裏插入圖片描述
在這裏插入圖片描述

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