当多个配置文件不活动时如何有条件地声明 Bean?

新手上路,请多包涵

在我的 Spring-Boot-App 中,我想有条件地声明一个 Bean,具体取决于(未)加载的 spring-profiles。

条件:

 Profile "a" NOT loaded
AND
Profile "b" NOT loaded

到目前为止我的解决方案(有效):

 @Bean
@ConditionalOnExpression("#{!environment.getProperty('spring.profiles.active').contains('a') && !environment.getProperty('spring.profiles.active').contains('b')}")
    public MyBean myBean(){/*...*/}

有没有更优雅(更短)的方式来解释这种情况?

特别是我想在这里摆脱Spring Expression Language的使用。

原文由 Mike Boddin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 348
2 个回答

从 Spring 5.1.4(并入 Spring Boot 2.1.2)开始,可以在配置文件字符串注释中使用配置文件表达式。所以:

Spring 5.1.4 (Spring Boot 2.1.2) 及更高版本 中,它很简单:

 @Component
@Profile("!a & !b")
public class MyComponent {}

Spring 4.x 和 5.0.x 中:

这个 Spring 版本有很多方法,每种方法都有其优点和缺点。当没有太多组合可以涵盖时,我个人喜欢 @Stanislav@Conditional 注释回答。

其他方法可以在这个类似的问题中找到:

Spring Profile - 如何包含添加 2 个配置文件的 AND 条件?

Spring:如何在 Profiles 中做 AND?

原文由 f-CJ 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您有一个配置文件,您可以简单地使用带有 not 运算符的 @Profile 注释。它也接受多个配置文件,但带有 OR 条件。

因此,替代解决方案是使用自定义 Condition@Conditional 注释。像这样:

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

    // Return true if NOT "a" AND NOT "b"
    return !context.getEnvironment().acceptsProfiles("a")
                  && !context.getEnvironment().acceptsProfiles("b");
  }
}

然后用它注释你的方法,比如:

 @Bean
@Conditional(SomeCustomCondition.class)
public MyBean myBean(){/*...*/}

原文由 Stanislav 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题