用Kotlin注释泉水

Kotlin不能在编译时注入注释,如现有的库Lombok 。 有没有什么体面的方式在运行时注入Spring框架?

假设您正在尝试将注入器注释注入到Spring应用程序中。

这里是注解类的例子: Log.kt

package com.example.util @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.FIELD) @MustBeDocumented annotation class Log 

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

 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 } } 

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

 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" } } 

为了避免在logger?.info('...')这样的空安全类中调用logger,这个例子使用了后期初始化的修饰符来标记属性。