Not able to read annotation property inside Aspect when writing pointcut in a method

401 views Asked by At

I have a custom annotation as

annotation class MyHandler(val value:String)

I wrote an aspect for functions using this annotation, also reading the value within the annotation for my processing.

    @Around("@annotation(myHandler)")
    fun handleExceptions(joinPoint: ProceedingJoinPoint, myHandler: MyHandler) {
        println(myHandler.value) //this works
        try {
            joinPoint.proceed()
        } catch (e: Exception){
        }
    }

This works perfectly fine.

I then tried to move the pointcut definition to a separate function as below and this is where I am running into issues.

    @Pointcut("@annotation(com.example.demo.MyHandler)")
    fun myHandlerFunc() {}
    
    @Around(value = "myHandlerFunc()")
    fun handleExceptions(joinPoint: ProceedingJoinPoint, myHandler: MyHandler) {
        println(myHandler.value) //this works
        try {
            joinPoint.proceed()
        } catch (e: Exception){
        }
    }

Error being -

Caused by: java.lang.IllegalArgumentException: error at ::0 formal unbound in pointcut.

Any way I could still have access to the annotation properties, while having the pointcut definition in a separate method?

1

There are 1 answers

2
mewan On

Got this to work after some trial and error

    @Pointcut("@annotation(myHandler)")
    fun myHandlerFunc(myHandler: MyHandler) {}

    @Around(value = "myHandlerFunc(myHandler)")
    fun handleExceptions(joinPoint: ProceedingJoinPoint, myHandler: MyHandler) {
        println(myHandler.value)
        try {
            joinPoint.proceed()
        } catch (e: Exception){
        }
    }

Is there a better or cleaner way to accomplish this?