How to use spring annotations like @Autowired in kotlin?

前端 未结 4 1066
孤城傲影
孤城傲影 2020-12-13 01:38

Is it possible to do something like following in Kotlin?

@Autowired
internal var mongoTemplate: MongoTemplate

@Autowired
internal var solrClient: SolrClient         


        
4条回答
  •  天命终不由人
    2020-12-13 01:57

    Recommended approach to do Dependency Injection in Spring is constructor injection:

    @Component
    class YourBean(
        private val mongoTemplate: MongoTemplate, 
        private val solrClient: SolrClient
    ) {
      // code
    }
    

    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
    }
    

    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
    }
    

    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.

    Links:

    1. Documentation on lateinit
    2. Documentation on constructors
    3. Developing Spring Boot applications with Kotlin

提交回复
热议问题