如何在kotlin中使用@Autowired这样的Spring注解?
是否有可能在Kotlin做下面的事情?
@Autowired internal var mongoTemplate: MongoTemplate @Autowired internal var solrClient: SolrClient
当然,这是可能的,你有几个选项,我建议带注释的构造函数,但是lateinit也可以,在一些情况下可能有用:
Lateinit:
@Component class YourBean { @Autowired lateinit var mongoTemplate: MongoTemplate @Autowired lateinit var solrClient: SolrClient }
构造函数:
@Component class YourBean @Autowired constructor( private val mongoTemplate: MongoTemplate, private val solrClient: SolrClient ) { // code }
Spring 4.3的构造函数:
@Component class YourBean( private val mongoTemplate: MongoTemplate, private val solrClient: SolrClient ) { // code }
构造器版本检查所有依赖关系在创建bean的时候和所有注入的字段 – val,在另一方面,lateinit注入的字段只能是var,并且运行时占用的空间很小。 而用测试类来测试,你不需要反思。
链接:
- 关于lateinit的文档
- 关于构造函数的文档
- 用Kotlin开发Spring Boot应用程序
是的,Java注释在Kotlin中大部分都支持Java。 一个问题是主构造函数中的注释需要显式的“构造函数”关键字:
从https://kotlinlang.org/docs/reference/annotations.html
如果您需要注释类的主构造函数,则需要将构造函数关键字添加到构造函数声明中,并在其之前添加注释:
class Foo @Inject constructor(dependency: MyDependency) { // ... }
- Kotlin无法在类中使用@Configuration @EnableWebMvc注释创建@Autowired字段
- 来自YML的ConfigurationProperties加载列表
- Spring REST,Kotin和默认的基本参数导致错误
- 带有Jetty + Jersey的Spring Boot始终显示404
- 使用Kotlin功能DSL编写导航配置
- 使用Spring HATEOAS ControllerLinkBuilder和Kotlin抛出IllegalArgumentException
- 在Kotlin中使用@Service时引发异常
- Spring Boot Kotlin Jersey ModelValidationException
- Spring Boot和Kotlin中的部分更新REST