Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to annotate class constructor in Kotlin

Clarification This questions was asked before kotlin hit version 1.0. Language syntax in example is obsolete now, please follow official docs.


I'm playing with kotlin and spring DI. I want to use constructor-based dependency injection, so I need to annotate the constructor.

I tried following approach:

Configuration
Import(javaClass<DataSourceConfig>())
public open class AppConfig(dataSource: DataSource) {
    private val dataSource: DataSource

    Autowired {
        this.dataSource = dataSource
    }
}

Configuration
public open class DataSourceConfig {

    Bean
    public open fun dataSource(): DataSource {
        // source omitted
    }

}

But it doesn't work. Is it even possible to annotate constructor in kotlin?

P.S. I'm using Kotlin M10.1 and Spring 4.1.4

UPDATE: Annotating constructor is possible in kotlin. The problem was that it's not allowed to use constructor-based DI for @Configuration

like image 530
ivstas Avatar asked Feb 08 '15 19:02

ivstas


2 Answers

Hrm, I think the syntax has changed radically since this question was posted. The current way (according to the docs) is to add the keyword constructor between your class name and arguments and annotate that, i.e.

public class AppConfig @Configuration constructor(dataSource: DataSource) {
    //...
}
like image 117
Max Avatar answered Oct 01 '22 18:10

Max


Try to write:

Configuration
public open class AppConfig [Import(javaClass<DataSourceConfig>())] (dataSource: DataSource) {
//...
}
like image 27
bashor Avatar answered Oct 01 '22 19:10

bashor