如何在 kotlin 中使用像 @Autowired 这样的 spring 注释? [英] How to use spring annotations like @Autowired in kotlin?
问题描述
是否可以在 Kotlin 中执行类似以下操作?
Is it possible to do something like following in Kotlin?
@Autowired
internal var mongoTemplate: MongoTemplate
@Autowired
internal var solrClient: SolrClient
推荐答案
推荐在 Spring 中进行依赖注入的方法是构造函数注入:
Recommended approach to do Dependency Injection in Spring is constructor injection:
@Component
class YourBean(
private val mongoTemplate: MongoTemplate,
private val solrClient: SolrClient
) {
// code
}
在 Spring 4.3 之前的构造函数应该用 Autowired
显式注释:
Prior to Spring 4.3 constructor should be explicitly annotated with Autowired
:
@Component
class YourBean @Autowired constructor(
private val mongoTemplate: MongoTemplate,
private val solrClient: SolrClient
) {
// code
}
在极少数情况下,您可能喜欢使用字段注入,您可以借助 lateinit
来实现:
In rare cases, you might like to use field injection, and you can do it with the help of lateinit
:
@Component
class YourBean {
@Autowired
private lateinit var mongoTemplate: MongoTemplate
@Autowired
private lateinit var solrClient: SolrClient
}
构造函数注入在bean创建时检查所有依赖项,所有注入的字段都是val
,另一方面,lateinit注入的字段只能是var
,并且运行时开销很小.用构造函数测试类,你不需要反射.
Constructor injection checks all dependencies at bean creation time and all injected fields is val
, at other hand lateinit injected fields can be only var
, and have little runtime overhead. And to test class with constructor, you don't need reflection.
链接:
这篇关于如何在 kotlin 中使用像 @Autowired 这样的 spring 注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!