[英]With Spring Boot 2.2+, how can you create a bean when the application is NOT running on a Cloud Platform
In Spring Boot 2.2 there is an annotation @ConditionalOnCloudPlatform
which can be used to detect whether the application is running on a Cloud Platform.在 Spring Boot 2.2 中有一个注解
@ConditionalOnCloudPlatform
可以用来检测应用程序是否在云平台上运行。
I have the reverse issue - I want to not run a bean which is running on a Cloud Platform.我有相反的问题 - 我不想运行在云平台上运行的 bean。 For example, I have code which I don't want to run when running on Kubernetes (as the platform where I run Kubernetes already supplies the functions in the given bean).
例如,我有代码在 Kubernetes 上运行时不想运行(因为我运行 Kubernetes 的平台已经提供给定 bean 中的功能)。
What's the best approach to do this?这样做的最佳方法是什么? I feel like I need a
@ConditionalOnCloudPlatform
annotation.我觉得我需要一个
@ConditionalOnCloudPlatform
注释。
Thanks.谢谢。
Use @ ConditionalOnMissingBean
with the name of Kubernetes bean of @ ConditionalOnMissingClass
with one of bean's (or related) classes.将
@ ConditionalOnMissingBean
与@ConditionalOnMissingClass 的名称为@ ConditionalOnMissingClass
bean 与bean 的(或相关的)类之一一起使用。
Solution 1解决方案 1
It seems you are using Spring Cloud Kubernetes
.看来您正在使用
Spring Cloud Kubernetes
。 If so, when an application runs as a pod inside Kubernetes a Spring profile named 'kubernetes' is automatically get activated.如果是这样,当应用程序作为 Kubernetes 内的 pod 运行时,名为“kubernetes”的 Spring 配置文件会自动激活。
@Component
@Profile("!kubernetes")
public class MyLocalTestBean {}
Solution 2解决方案 2
Invert condition using NonNestedConditions (the code below is not verified)使用NonNestedConditions反转条件(下面的代码未经验证)
class ConditionalOnNotInCloud extends NoneNestedConditions {
ConditionalOnNotInCloud() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnCloudPlatform
static class OnCloudCondition {
}
}
@Bean
@Conditional(ConditionalOnNotInCloud.class)
public StubBean createStubBean() {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.