使用Kotlin的Spring注释注入

使用Kotlin的Spring注释注入,spring,logging,annotations,kotlin,Spring,Logging,Annotations,Kotlin,Kotlin无法在编译时(如通过现有库)注入注释。是否有合适的方法在运行时为spring framework注入注释?假设您正在尝试将记录器注释注入spring应用程序 下面是注释类示例:Log.kt 此类在运行时注入注释:LogInjector.kt 然后,这个类使用@Log注释:GreetingController.kt 为了避免在null-safe中调用记录器,如logger?.info(“…”),此示例将属性标记为 package com.example.util @Retention(

Kotlin无法在编译时(如通过现有库)注入注释。是否有合适的方法在运行时为spring framework注入注释?

假设您正在尝试将记录器注释注入spring应用程序

下面是注释类示例:Log.kt

此类在运行时注入注释:LogInjector.kt

然后,这个类使用
@Log
注释:GreetingController.kt

为了避免在null-safe中调用记录器,如
logger?.info(“…”)
,此示例将属性标记为

package com.example.util
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FIELD)
@MustBeDocumented
annotation class Log
package com.example.util
import org.slf4j.LoggerFactory
import org.springframework.beans.BeansException
import org.springframework.beans.factory.config.BeanPostProcessor
import org.springframework.stereotype.Component
import org.springframework.util.ReflectionUtils
import java.lang.reflect.Field

@Component
class LogInjector: BeanPostProcessor {

  @Throws(BeansException::class)
  override fun postProcessAfterInitialization(bean: Any, beanName: String): Any {
    return bean
  }

  @Throws(BeansException::class)
  override fun postProcessBeforeInitialization(bean: Any, name: String): Any {
    ReflectionUtils.doWithFields(bean.javaClass,
      @Throws(IllegalArgumentException::class, IllegalAccessException::class) { field: Field ->
        // SAM conversion for Java interface 
        ReflectionUtils.makeAccessible(field)
        if (field.getAnnotation(Log::class.java) != null) {
          val log = LoggerFactory.getLogger(bean.javaClass)
          field.set(bean, log)
        }
      }
    )
    return bean
  }
}
package com.example.web
import org.slf4j.Logger
import org.springframework.web.bind.annotation.*

@RestController
class GreetingController {
  @Log lateinit private var logger: Logger

  @RequestMapping("/greeting")
  fun greeting(): String {
    logger.info("Greeting endpoint was called")
    return "Hello"
  }
}