当多个配置文件未处于活动状态时如何有条件地声明 Bean? [英] How to conditionally declare Bean when multiple profiles are not active?

查看:24
本文介绍了当多个配置文件未处于活动状态时如何有条件地声明 Bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Spring-Boot-App 中,我想根据(未)加载的 spring-profiles 有条件地声明一个 Bean.

条件:

未加载配置文件a"和配置文件b"未加载

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

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

有没有更优雅(更简短)的方式来解释这种情况?
尤其是想把这里的Spring Expression Language的用法去掉.

解决方案

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

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

@Component@Profile("!a & !b")公共类 MyComponent {}

Spring 4.x 和 5.0.x 中:

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

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

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

Spring:如何在 Profiles 中做 AND?>

In my Spring-Boot-App I want to conditionally declare a Bean, depending on (un)loaded spring-profiles.

The conditon:

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

My solution so far (which works):

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

Is there a more elegant (and shorter) way to explain this condition?
Especially I want to get rid of the usage of Spring Expression Language here.

解决方案

Since Spring 5.1.4 (incorporated in Spring Boot 2.1.2) it is possible to use a profile expression inside profile string annotation. So:

In Spring 5.1.4 (Spring Boot 2.1.2) and above it is as easy as:

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

In Spring 4.x and 5.0.x:

There are many approaches for this Spring versions, each one of them has its pro's and con's. When there aren't many combinations to cover I personally like @Stanislav answer with the @Conditional annotation.

Other approaches can be found in this similar questions:

Spring Profile - How to include AND condition for adding 2 profiles?

Spring: How to do AND in Profiles?

这篇关于当多个配置文件未处于活动状态时如何有条件地声明 Bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆