我想使用@OnConditional*家族注释将我的Spring Boot App的代码逻辑地划分为几个“特性”。
我发现自己重复了很多代码,比如:
@ConditionalOnProperty( prefix = "pib2.war.features.", value = "hello", matchIfMissing = false )
@RestController
public class HelloController {
...
}为了简化维护,我想定义元注释,这样我就可以创建某种“功能切换”,比如:
@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 { };
}这样我的代码就变成了:
@FeatureToggle( "hello" )
@RestController
public class HelloController {
...
}但这似乎不起作用:OnPropertyCondition求值代码忽略了by @Aliased字段,它只是说名称为空:
...
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`”那样编写自己的条件求值器?
发布于 2020-07-01 06:25:12
如果您想编写自己的条件,则应该实现org.springframework.context.annotation.Condition
这是通过定义一个实现Condition接口的ProfileCondition类来实现@Profile的工作方式:
@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();
}https://stackoverflow.com/questions/62579394
复制相似问题