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

标签 spring spring-boot

在我的 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/

相关文章:

java - Spring aop 切入点表达式访问方法返回类型

spring-boot - 无法在应用程序属性中设置 cron 作业计划。 SpringBoot ;使用调度程序在运行时调度 cron 作业

java - Spring Boot Web无法将嵌套的json解析为对象

java - 如何在基于java的docker镜像中安装包管理器

spring boot 覆盖默认的 REST 异常处理程序

java - Spring Boot和Spring Cloud配置客户端错误

java - React Native 和 Java 之间的 WebSocket

java - spring-boot-starter-web 和 spring-boot-starter-web-services 和 spring-boot-starter-jersey 之间的区别

java - 无法解析值 'spring.profiles.active' 中的占位符 "classpath:/ldap-${spring.profiles.active}.properties"

java - 如何在单元测试中设置不同的类路径以使用 Spring 加载资源