首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我可以将@ConditionalProperty与我的自定义注释一起使用,以避免重复配置吗?

我可以将@ConditionalProperty与我的自定义注释一起使用,以避免重复配置吗?
EN

Stack Overflow用户
提问于 2020-06-25 23:54:38
回答 1查看 278关注 0票数 1

我想使用@OnConditional*家族注释将我的Spring Boot App的代码逻辑地划分为几个“特性”。

我发现自己重复了很多代码,比如:

代码语言:javascript
复制
@ConditionalOnProperty( prefix = "pib2.war.features.", value = "hello", matchIfMissing = false )
@RestController
public class HelloController {
...
}

为了简化维护,我想定义元注释,这样我就可以创建某种“功能切换”,比如:

代码语言:javascript
复制
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ConditionalOnProperty( prefix = "pib2.war.features" )
public @interface FeatureToggle {

    @AliasFor(annotation = ConditionalOnProperty.class )
    String[] value() default { };

    @AliasFor(annotation = ConditionalOnProperty.class )
    String[] name() default { };
}

这样我的代码就变成了:

代码语言:javascript
复制
@FeatureToggle( "hello" )
@RestController
public class HelloController {
...
}

但这似乎不起作用:OnPropertyCondition求值代码忽略了by @Aliased字段,它只是说名称为空:

代码语言:javascript
复制
...
Caused by: java.lang.IllegalStateException: The name or value attribute of @ConditionalOnProperty must be specified
    at org.springframework.util.Assert.state(Assert.java:73)
    at org.springframework.boot.autoconfigure.condition.OnPropertyCondition$Spec.getNames(OnPropertyCondition.java:129)
    at org.springframework.boot.autoconfigure.condition.OnPropertyCondition$Spec.<init>(OnPropertyCondition.java:122)
    at org.springframework.boot.autoconfigure.condition.OnPropertyCondition.determineOutcome(OnPropertyCondition.java:88)
    at org.springframework.boot.autoconfigure.condition.OnPropertyCondition.getMatchOutcome(OnPropertyCondition.java:55)
    at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:47)
    ... 90 common frames omitted

所以我猜创建这些快捷的元注注是不可能的?我的配置是不是错了?我是否应该像“OnPropertyCondition`”那样编写自己的条件求值器?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-01 06:25:12

如果您想编写自己的条件,则应该实现org.springframework.context.annotation.Condition

这是通过定义一个实现Condition接口的ProfileCondition类来实现@Profile的工作方式:

代码语言:javascript
复制
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(ProfileCondition.class)
public @interface Profile {

    /**
     * The set of profiles for which the annotated component should be registered.
     */
    String[] value();

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62579394

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档