Spring自定义@ConditionalOnProperty批注不能使用@AliasFor

时间:2019-09-02 09:21:48

标签: spring spring-boot kotlin

我想为我的项目创建FeatureFlag注释,以避免代码重复。

我创建了一个名为FeatureFlag的新注释。我用通用前缀ConditionalOnProperty的{​​{1}}注解修饰。我向注解中添加了新字段,即foo.featuresAliasFor字段。据我所知,以下代码应该可以,但是不能。我还测试了ConditionalOnProperty批注上的别名,并且可以正常工作。

Profile

在运行测试用例时,出现以下错误: 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" } } java.lang.IllegalStateException: The name or value attribute of @ConditionalOnProperty must be specified批注应包含FeatureFlag字段的值。)

您能帮忙吗,我做错了什么?这是框架中的错误吗?

1 个答案:

答案 0 :(得分:0)

除了前缀属性,您还需要在ConditionalOnProperty批注中定义名称或值属性,以使其起作用。

在这里查看您使用的注释的详细信息:https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/condition/ConditionalOnProperty.html