Search code examples
kotlinmicronaut

Use @ConfigurationProperties in Annotation parameter/ argument? (must be compile-time constant)


I´m trying to use a Configuration in an Annotation, like so:

@ConfigurationProperties("scheduling")
interface SchedulingConfiguration {
    val initialDelay: String
    val fixedDelay: String
}

@Singleton
class Worker(
    private val configuration: SchedulingConfiguration,
) {
    private val log = LoggerFactory.getLogger(javaClass)

    @Scheduled(initialDelay = configuration.initialDelay, fixedDelay = configuration.fixedDelay)
    fun fetchQueueEntry() {
        log.info("Fetching entry")
    }
}

I´m getting the warning An annotation argument must be a compile-time constant.

Is there some way to get this working with Micronaut?


Solution

  • I managed to get it running by browsing the Micronaut documentation and accidentally stumbling across Property Placeholders. This will work fine, even though not feeling 'optimal'.

    @Singleton
    class Worker {
        private val log = LoggerFactory.getLogger(javaClass)
    
        @Scheduled(
            initialDelay = "\${scheduling.initialDelay}",
            fixedDelay = "\${scheduling.fixedDelay}"
        )    
        fun fetchQueueEntry() {
            log.info("Fetching entry")
        }
    }
    

    It´s also possible to define default values that will be used if the keys are not present in config files or env variables:

        @Scheduled(
            initialDelay = "\${scheduling.initialDelay:0s}",
            fixedDelay = "\${scheduling.fixedDelay:10s}"
        )    
    

    With no default values and absent configuration for used property placeholders, an Exception will be thrown at runtime and the application will shut down.