如何在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