仅在指定属性或值时注册 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();
    }
}