12

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

1
  • My only question is Why are you using M10? There's a version 1 beta 4 out right now that should work better. You don't have to actually answer this. I was just surprised see a milestone release being used still. Jan 3, 2016 at 5:06

3 Answers 3

22

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) {
    //...
}
1

Try to write:

Configuration
public open class AppConfig [Import(javaClass<DataSourceConfig>())] (dataSource: DataSource) {
//...
}
1
  • the problem is not Import annotation, it works. The problem is that spring is trying to access default-constructor (which obviously fails) - which means it doesn't find any annotated non-default constructor.
    – ivstas
    Feb 9, 2015 at 12:21
0

This syntax works for me:

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

  Autowired constructor(dataSource: DataSource){
    this.dataSource = dataSource
  }
}
1
  • 1
    This approach is not working for me. First the compiler complains that "Primary constructor call is expected". Then if I add this() call to the constructor, it complains that "Val cannot be reassigned". Using kotlin version 0.11.91.1. Tx Apr 26, 2015 at 13:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.