2
votes

I want to create FeatureFlag annotation for my project to avoid code repetitions.

I created a new annotation called FeatureFlag. I decorated with ConditionalOnProperty annotation with the generic prefix foo.features. I add new fields to the annotation, which is AliasFor the ConditionalOnProperty fields. As far as I know, the following code should work, but it does not. I also tested the aliasing on the Profile annotation and that is working.


import io.kotlintest.shouldBe
import org.junit.jupiter.api.Test
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.annotation.AliasFor

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@ConditionalOnProperty(prefix = "foo.features")
annotation class FeatureFlag(
    @get:AliasFor(annotation = ConditionalOnProperty::class, value = "name") val feature: String,
    @get:AliasFor(annotation = ConditionalOnProperty::class, value = "havingValue") val enabled: String = "true"
)

@SpringBootTest(
    properties = ["foo.features.dummy: true"],
    classes = [FeatureFlagTest.FeatureFlagTestConfiguration::class]
)
class FeatureFlagTest(private val applicationContext: ApplicationContext) {

    @Configuration
    class FeatureFlagTestConfiguration {

        @Bean
        @FeatureFlag(feature = "dummy")
        fun positive(): String = "positive"

        @Bean
        @FeatureFlag(feature = "dummy", enabled = "false")
        fun negative(): String = "negative"
    }

    @Test
    fun `test`() {
        applicationContext.getBean(String::class.java) shouldBe "positive"
    }
}

When I running the test case I get the following error: java.lang.IllegalStateException: The name or value attribute of @ConditionalOnProperty must be specified (The FeatureFlag annotation should contain the value of the name field.)

Can you help, what did I wrong? Is it a bug in the framework?

1

1 Answers

0
votes

In addition to the prefix attribute, you also need to define the name or value attribute in the ConditionalOnProperty annotation in order for it to work.

Have a look here to see the details of the annotation you're using: https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/condition/ConditionalOnProperty.html