kotlin 如何获取方面中的注解属性值?

djp7away  于 2023-03-13  发布在  Kotlin
关注(0)|答案(2)|浏览(169)

注解定义:

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

方面:

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

使用注解:

@RequireEnabledFeature("something")
fun someFction()

现在的问题是如何在Kotlin中获得特征名称值?在点切割中注入注解对象也不起作用。有什么想法吗?看起来使用joinPoint我可以获得joinPoint.target.javaClass.methods[1].annotations[0],这是AnnotationInvocationHandler的代理,但我不能从那里获得属性值。

gmxoilav

gmxoilav1#

在@Around函数中给予一下:

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

rbl8hiat2#

只需将注解绑定到一个通知方法参数,如下所示(我不会说Kotlin语,所以我在编写时没有编译它):

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

相关问题