如何在 kotlin 中使用像 @Autowired 这样的 spring 注释?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35479631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use spring annotations like @Autowired in kotlin?
提问by eendroroy
Is it possible to do something like following in Kotlin?
是否可以在 Kotlin 中执行以下操作?
@Autowired
internal var mongoTemplate: MongoTemplate
@Autowired
internal var solrClient: SolrClient
回答by Ruslan
Recommended approach to do Dependency Injection in Spring is constructor injection:
在 Spring 中进行依赖注入的推荐方法是构造函数注入:
@Component
class YourBean(
private val mongoTemplate: MongoTemplate,
private val solrClient: SolrClient
) {
// code
}
Prior to Spring 4.3 constructor should be explicitly annotated with Autowired
:
在 Spring 4.3 构造函数之前,应显式注释Autowired
:
@Component
class YourBean @Autowired constructor(
private val mongoTemplate: MongoTemplate,
private val solrClient: SolrClient
) {
// code
}
In rare cases, you might like to use field injection, and you can do it with the help of lateinit
:
在极少数情况下,您可能喜欢使用字段注入,您可以在以下帮助下进行lateinit
:
@Component
class YourBean {
@Autowired
private lateinit var mongoTemplate: MongoTemplate
@Autowired
private lateinit var solrClient: SolrClient
}
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.
构造函数注入在 bean 创建时检查所有依赖项,所有注入的字段 is val
,另一方面,lateinit 注入的字段只能是var
,并且运行时开销很小。并且要使用构造函数测试类,您不需要反射。
Links:
链接:
回答by Mike Buhot
Yes, java annotations are supported in Kotlin mostly as in Java. One gotcha is annotations on the primary constructor requires the explicit 'constructor' keyword:
是的,与 Java 一样,Kotlin 主要支持 Java 注释。一个问题是主构造函数上的注释需要显式的 'constructor' 关键字:
From https://kotlinlang.org/docs/reference/annotations.html
来自https://kotlinlang.org/docs/reference/annotations.html
If you need to annotate the primary constructor of a class, you need to add the constructor keyword to the constructor declaration, and add the annotations before it:
如果需要对类的主构造函数进行注解,则需要在构造函数声明中添加constructor关键字,并在其前添加注解:
class Foo @Inject constructor(dependency: MyDependency) {
// ...
}
回答by Mr.Turtle
You can also autowire dependencies through the constructor. Remember to annotate your dependencies with @Configuration, @Component, @Service
etc
您还可以通过构造函数自动装配依赖项。记得用@Configuration, @Component, @Service
etc注释你的依赖项
import org.springframework.stereotype.Component
@Component
class Foo (private val dependency: MyDependency) {
//...
}