Home > Enterprise >  How to get annotation property value in the aspect?
How to get annotation property value in the aspect?

Time:09-03

Annotation definition:

@Target(AnnotationTarget.FUNCTION)
annotation class RequireEnabledFeature(val featureName:String) {
}

Aspect:

@Aspect
@Component
class RequireEnabledFeatureAspect {
    @Around(
        value = "execution(public * *(..)) && @annotation(RequireEnabledFeature)"
    )
    fun requireEnabledFeature(joinPoint: ProceedingJoinPoint): Any? {
        return joinPoint.proceed()
    }
}

Using the annotation:

@RequireEnabledFeature("something")
fun someFction() 

Now the question is how can I get the feature name value in Kotlin? Injecting annotation object in the point cut was also not working. Any idea? It seems like using joinPoint I can get joinPoint.target.javaClass.methods[1].annotations[0] which is the Proxy for AnnotationInvocationHandler but I am not unable to get the propert value from there.

CodePudding user response:

Give this a try in your @Around function:

val theMethod = (joinPoint.signature as MethodSignature).method
val myAnnotation = theMethod.getAnnotation(RequireEnabledFeature::class.java)
println(myAnnotation.featureName) // here you get the annotation's properties

CodePudding user response:

Just bind the annotation to an advice method parameter like this (I do not speak Kotlin, so I am writing this without having compiled it):

@Around("execution(public * *(..)) && @annotation(feature)")
fun requireEnabledFeature(joinPoint: ProceedingJoinPoint, RequireEnabledFeature feature): Any? {
  println(feature.featureName)
  return joinPoint.proceed()
}
  • Related