僅在指定屬性或值時註冊 bean

可以配置 spring bean,使其在具有特定值滿足指定屬性時才會註冊。為此,請實施 Condition.matches 以檢查屬性/值:

public class PropertyCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return context.getEnvironment().getProperty("propertyName") != null;
        // optionally check the property value
    }
}

在 Java 配置中,使用上面的實現作為註冊 bean 的條件。注意使用 @Conditional 註釋。

@Configuration
public class MyAppConfig {

    @Bean
    @Conditional(PropertyCondition.class)
    public MyBean myBean() {
      return new MyBean();
    }
}

PropertyCondition 中,可以評估任何數量的條件。但是,建議將每個條件的實現分開,以使它們鬆散耦合。例如:

@Configuration
public class MyAppConfig {

    @Bean
    @Conditional({PropertyCondition.class, SomeOtherCondition.class})
    public MyBean myBean() {
      return new MyBean();
    }
}