加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

带有数组元素的Java自定义注释

发布时间:2020-12-15 01:47:02 所属栏目:大数据 来源:网络整理
导读:我有一个自定义注释如下. @Retention(RetentionPolicy.RUNTIME)@Target({ ElementType.TYPE,ElementType.METHOD })@Documented@Conditional(OnApiVersionConditional.class)public @interface ConditionalOnApiVersion { int[] value() default 5; String pr

我有一个自定义注释如下.

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE,ElementType.METHOD })
@Documented
@Conditional(OnApiVersionConditional.class)
public @interface ConditionalOnApiVersion {

    int[] value() default 5;

    String property();
}

OnApiVersionConditional是,

public class OnApiVersionConditional implements Condition {

  @Override
    public boolean matches(final ConditionContext context,final AnnotatedTypeMetadata metadata) {
        final MultiValueMap

在我的Bean注释中,

  @Bean
  @ConditionalOnApiVersion(value = {6,7},property = "userInputVersion")

还有像单一版本匹配的bean

@Bean
@ConditionalOnApiVersion(value = 8,property = "userInputVersion")

我想验证属性文件中的userInput版本到可用的Beans支持版本.不确定,如何获取值,迭代并与userInoutVersion进行比较.该值可以是8或{6,7}作为int数组.不确定,如何迭代该值以检查是否有任何值与输入版本匹配.

final List apiVersions = attributes.get(“value”).stream().collect(Collectors.toList());

题:

如何迭代attributes.get(“value”)并与userInputVersion进行比较?

attributes.get(“value”)返回一个Object列表.

我试过下面的代码,

final List

但得到以下错误在第二行anyMatch,

java.lang.ClassCastException: [I cannot be cast to java.lang.Integer

谢谢

最佳答案
您已经定义了一个使用Spring的@Conditional的良好自定义注释,如果数组值中存在名为“property”的属性,则此过程将仅创建bean.

注释定义了这两个变量如下:

> value:int [](一个或多个受支持的版本)
> property:String(要比较的属性的名称)

当您使用元数据检索这些值时,Spring会将它们作为对象返回.将这些对象转换为您定义它们的类型是关键步骤.不需要流,因为迭代int []数组是微不足道的.

我测试了各种形式的注释(值= 5,值= {6,7}等)并发现以下代码运行良好(仅在版本正确时才创建@Conditional bean).

public class OnApiVersionConditional implements Condition {

@Override
public boolean matches(final ConditionContext context,final AnnotatedTypeMetadata metadata) {

    final MultiValueMap

通过验证属性和值可以改进这种方法;如果其中任何一个包含错误/空值等,则返回false.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读