首页 > 解决方案 > How to add arguments to Spring AOP aspect

问题描述

In Kotlin language, I configured a Spring AOP annotation like this:

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)

annotation class Authenticated(val roles: Array<String>)

... and the aspect class like this:

@Aspect
@Component
class AuthenticationAspect {

    @Around("@annotation(Authenticated) && args(roles)", argNames = "roles")
    @Throws(Throwable::class)
    fun authenticate(joinPoint: ProceedingJoinPoint, roles: Array<String>):Any? {
            //.. do stuff
            return proceed
    }
}

And in my methods I add the annotation like this:

@Authenticated(roles = ["read", "write"])
fun someMethod(msg: Pair) {
   // do stuff...
}

The annotation works well without arguments, i.e., the annotated method gets intercepted. But with the argument "roles" it never gets matched and I have no clue why. Any help would be much appreciated.

标签: aopaspectjspring-aop

解决方案


当您使用“&& args(roles)”时,您是在目标方法中查找名为“roles”的参数,而不是在注释中。

您可以尝试将您的方面更改为以下内容:

@Around("@annotation(authenticated))
@Throws(Throwable::class)
fun authenticate(joinPoint: ProceedingJoinPoint, authenticated: Authenticated):Any? {
    val roles = authenticated.roles
    //.. do stuff
    return proceed
}

推荐阅读