如何在Kotlin中使用@Autowired之类的弹簧注释? [英] How to use spring annotations like @Autowired in kotlin?

查看:1453
本文介绍了如何在Kotlin中使用@Autowired之类的弹簧注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在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的帮助下完成此操作:

I rare cases you might like to use field injection, and you can do it with 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.

链接:

  1. lateinit上的文档
  2. 关于构造函数的文档
  3. 使用Kotlin开发Spring Boot应用程序
  1. Documentation on lateinit
  2. Documentation on constructors
  3. Developing Spring Boot applications with Kotlin

这篇关于如何在Kotlin中使用@Autowired之类的弹簧注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆