如何在kotlin中使用像@Autowired这样的弹簧注释?

een*_*roy 61 spring kotlin

是否有可能在Kotlin做类似的事情?

@Autowired
internal var mongoTemplate: MongoTemplate

@Autowired
internal var solrClient: SolrClient
Run Code Online (Sandbox Code Playgroud)

Rus*_*lan 141

肯定这是可能的,你有几个选项,我建议使用带注释的构造函数,但是lateinit也可以工作,在某些情况下可能有用:

Lateinit:

@Component
class YourBean {

    @Autowired
    lateinit var mongoTemplate: MongoTemplate

    @Autowired
    lateinit var solrClient: SolrClient
}
Run Code Online (Sandbox Code Playgroud)

构造函数:

@Component
class YourBean @Autowired constructor(
    private val mongoTemplate: MongoTemplate, 
    private val solrClient: SolrClient
) {
  // code
}
Run Code Online (Sandbox Code Playgroud)

Spring 4.3的构造函数:

@Component
class YourBean(
    private val mongoTemplate: MongoTemplate, 
    private val solrClient: SolrClient
) {
  // code
}
Run Code Online (Sandbox Code Playgroud)

构造函数版本检查bean创建时的所有依赖关系以及所有注入的字段 - val,另一方面,lateinit注入的字段只能是var,并且运行时占用空间很小.要使用构造函数测试类,您不需要反射.

链接:

  1. 关于lateinit的文档
  2. 关于构造函数的文档
  3. 使用Kotlin开发Spring Boot应用程序


Yih*_*Gao 9

如果您想要属性注入但不喜欢lateinit var,这是我使用属性委托的解决方案:

private lateinit var ctx: ApplicationContext

@Component
private class CtxVarConfigurer : ApplicationContextAware {
    override fun setApplicationContext(context: ApplicationContext) {
        ctx = context
    }
}

inline fun <reified T : Any> autowired(name: String? = null) = Autowired(T::class.java, name)

class Autowired<T : Any>(private val javaType: Class<T>, private val name: String?) {

    private val value by lazy {
        if (name == null) {
            ctx.getBean(javaType)
        } else {
            ctx.getBean(name, javaType)
        }
    }

    operator fun getValue(thisRef: Any?, property: KProperty<*>): T = value

}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用更好的by委托语法:

@Service
class MyService {

    private val serviceToBeInjected: ServiceA by autowired()

    private val ambiguousBean: AmbiguousService by autowired("qualifier")

}
Run Code Online (Sandbox Code Playgroud)


Mik*_*hot 6

是的,Kotlin支持Java注释,主要是在Java中.一个问题是主构造函数上的注释需要显式的'constructor'关键字:

来自https://kotlinlang.org/docs/reference/annotations.html

如果需要注释类的主要构造函数,则需要将constructor关键字添加到构造函数声明中,并在其前面添加注释:

class Foo @Inject constructor(dependency: MyDependency) {
  // ...
}
Run Code Online (Sandbox Code Playgroud)


小智 6

像那样

@Component class Girl( @Autowired var outfit: Outfit)
Run Code Online (Sandbox Code Playgroud)

  • @vigamage Kotlin 不需要主构造函数使用“constructor”关键字。 (2认同)

Mr.*_*tle 5

您还可以通过构造函数自动装配依赖项。记得用@Configuration, @Component, @Serviceetc注释你的依赖关系

import org.springframework.stereotype.Component

@Component
class Foo (private val dependency: MyDependency) {
    //...
}
Run Code Online (Sandbox Code Playgroud)