Search code examples
kotlinconfigquarkus

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?


Solution

  • 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
    }