ConditionalOnMissingBean按类和名称

时间:2018-03-20 11:09:28

标签: spring spring-boot

我想在缺少具有特定名称的特定类类型时创建bean,但下面的ConditionalOnMissingBean不起作用,因为值和名称不相关。

@ConditionalOnMissingBean(value=BeanName.class, name = "beanName")

1 个答案:

答案 0 :(得分:2)

盒子没有这样的功能。但是,您可以使用自定义Conditional轻松实现它:

class MyCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {

      String[] beanNames = context.getBeanFactory().getBeanNamesForType(BeanName.class);

      return Stream.of(beanNames).anyMatch(beanName -> beanName.equals("beanName"));
    }
  }

并将其添加到您的bean @Conditional(MyCondition.class)