Robin Trietsch
Robin Trietsch

Reputation: 1852

Injecting Spring Boot properties into Kotlin Singleton / object

I have a Spring Boot 2 project, and I'm using Kotlin. What I want to achieve, is to have a Kotlin singleton (i.e. an object) and inject Spring properties.

Normally, I'd do this using constructor injection, which is the preferred way. However, for objects, constructors are not allowed. Another option is to use lateinit var combined with @Value("\${my.property.name}"), though then I'd have to initialize the field or explicitly set the type.

I could not find an example or similar situation for this, so I'm curious what the required approach is for this use case.

Upvotes: 5

Views: 3710

Answers (1)

Adam Arold
Adam Arold

Reputation: 30548

Technically you can do this:

object MyObject {

    lateinit var foo: String
}

@Configuration
class BeanConfiguration {

    @Bean
    fun myObject(): MyObject {
        return MyObject.also {
            it.foo = "foo"
        }
    }
}

but I wouldn't recommend this approach as it seems like a code smell. It is better to have simple classes as Spring guarantees that methods annotated with @Bean will only be called once (if they don't have a prototype scope).

Since objects don't need to be created you can manage its own lifecycle if you want, you don't need to put all your things in Spring.

Upvotes: 3

Related Questions