Marc
Marc

Reputation: 1629

How do I set a config property in quarkus kotlin

In quarkus Java you can set a configuration property by defining it in application.properties. This can be used in some class like this:

@ApplicationScoped
public class SomeClass {
    @ConfigProperty(name = "some.config")
    String someConfig;
}

How do you achieve the same in Kotlin?

Upvotes: 5

Views: 2713

Answers (2)

geoand
geoand

Reputation: 64011

The one to one conversion to Kotlin would yield:

import org.eclipse.microprofile.config.inject.ConfigProperty
import jakarta.enterprise.context.ApplicationScoped

@ApplicationScoped
open class SomeClass {

    @field:ConfigProperty(name = "some.config")
    lateinit var someConfig: String
}

However, it would look much better if you use constructor injection like so:

import org.eclipse.microprofile.config.inject.ConfigProperty
import jakarta.enterprise.context.ApplicationScoped

@ApplicationScoped
open class SomeClass(@ConfigProperty(name = "some.config") val someConfig: String) {

}

Once defined, usage in an other class:

import jakarta.ws.rs.GET
import jakarta.ws.rs.Path
import jakarta.ws.rs.Produces
import jakarta.ws.rs.core.MediaType
import jakarta.inject.Inject
import jakarta.enterprise.inject.Default

@Path("/hello")
class GreetingResource {

    @Inject
    @field: Default 
    lateinit var service: SomeClass

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    fun hello() = "Hello from " + service.someConfig
}

Or again using constructor injection:

import jakarta.ws.rs.GET
import jakarta.ws.rs.Path
import jakarta.ws.rs.Produces
import jakarta.ws.rs.core.MediaType
import jakarta.inject.Inject
import jakarta.enterprise.inject.Default

@Path("/hello")
class GreetingResource(
    val service: SomeClass
) {
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    fun hello() = "Hello from " + service.someConfig
}

Upvotes: 10

Marc
Marc

Reputation: 1629

Geoand's answer is correct. What I ended up using was a slightly less verbose version that I personally prefer.

@ApplicationScoped
class SomeClass {
    @ConfigProperty(name = "some.config")
    lateinit var someConfig: String
}

Upvotes: 2

Related Questions