当多个配置文件处于非活动状态时,如何有条件地声明Bean? [英] How to conditionally declare Bean when multiple profiles are not active?
问题描述
在我的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的使用.
从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版本有很多方法,每种方法都有其优点和缺点.当涉及的组合不多时,我个人喜欢 Spring Profile-如何包含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屋!