gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:47:50 26 4
gpt4 key购买 nike

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

条件:

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 版本有很多方法,每一种都有其优缺点。当没有太多组合可以涵盖时,我个人喜欢@Stanislav answer带有 @Conditional 注释。

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

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

Spring: How to do AND in Profiles?

关于spring - 当多个配置文件不活动时如何有条件地声明 Bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35429168/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com