在String为null的情况下,有条件地创建Bean

时间:2018-01-04 17:50:26

标签: java spring

在String为null的情况下,如何有条件地创建Bean?

以下示例会导致错误,但我想以某种方式通过仅在评估的字符串不为空时创建bean来防止它发生。

public class MyAppContext

  @Value("${this.string.is.null}")
  private String nullString;

  @SupressWarnings("SpringJavaAutowiringInspection")
  @Bean
  public MessageListenerContainer myQueue() {
    bean.setDestinationName(nullString)
  }

2 个答案:

答案 0 :(得分:3)

您可以使用@ConditionalOnExpression注释:

@Bean
@ConditionalOnExpression("'${this.string.is.null}'!=null")
public MessageListener myQueue() {
    bean.setDestinationName(nullString)
}

或创建自定义条件:

public class MyPropNotNull implements Condition {

    public MyPropNotNull() {}

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment env = context.getEnvironment();
        return env.getProperty("this.string.is.null") != null;
    }
}

@Bean
@Conditional(MyPropNotNull.class)
public MessageListener myQueue() {
    bean.setDestinationName(nullString)
}

更新:如果有这种类型的bean是必需的,请不要忘记添加一个回退bean。例如:

 @ConditionalOnMissingBean
 @Bean
 public MessageListener useThisOneWhenTheOtherIsMissing() {
     // this bean will be used when the other one is not available
     // ...
 }

答案 1 :(得分:0)

尝试https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/condition/ConditionalOnProperty.html

.repeating-grid {
  position: absolute;
  top: 0; bottom: 0;
  left: 0; right: 0;
  background-size: $major-grid-size $major-grid-size;
  background-image:
    repeating-linear-gradient(0deg, $major-grid-color, $major-grid-color $major-grid-weight, transparent $major-grid-weight, transparent $major-grid-size),
    repeating-linear-gradient(-90deg, $major-grid-color, $major-grid-color $major-grid-weight, transparent $major-grid-weight, transparent $major-grid-size),
    repeating-linear-gradient(0deg, $minor-grid-color, $minor-grid-color $minor-grid-weight, transparent $minor-grid-weight, transparent $minor-grid-size),
    repeating-linear-gradient(-90deg, $minor-grid-color, $minor-grid-color $minor-grid-weight, transparent $minor-grid-weight, transparent $minor-grid-size);

  background-position: 15px 0;
}