使用 SpEL 作为注释值

问题描述

这是我的注释类:

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class ExternalCallMonitor(val system: String,val function: String)

使用SpEL设置注解值如下;

    @ExternalCallMonitor(system = "#{@url.getHost()}",function = "#{@url.getPath()}")
    fun methodWithUrlParameter(url: URL) {
        // Do nothing
    }

尝试按如下方式获取 Aspect 中的值

@Around("@annotation(aspect.external.ExternalCallMonitor)")
@Throws(Throwable::class)
fun externalCallMonitor(joinPoint: ProceedingJoinPoint): Any? {
    val methodName = joinPoint.signature.name
    val signature = joinPoint.signature as MethodSignature
    val method = joinPoint.target.javaClass.getmethod(signature.method.name,URL::class.java)
    val annotation = method.getAnnotation(ExternalCallMonitor::class.java)
    val host = annotation.system

host 应该是 localhost 在这里但我得到 "#{@url.getHost()}"

解决方法

您需要使用 BeanExpressionResolver(例如 StandardBeanExpressionResolver)来处理 SpEL。