英文:
With Spring Boot 2.2+, how can you create a bean when the application is NOT running on a Cloud Platform
问题
在Spring Boot 2.2中,有一个名为@ConditionalOnCloudPlatform
的注解,可用于检测应用是否在云平台上运行。
我有相反的需求 - 我希望不运行在云平台上运行的bean。例如,我有一些代码,当在Kubernetes上运行时,我不希望运行它(因为我在运行Kubernetes的平台已经提供了给定bean中的功能)。
如何处理这种情况最佳?我觉得我需要一个@ConditionalOnCloudPlatform
注解。
谢谢。
英文:
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.
I have the reverse issue - I want to not run a bean which is running on a Cloud Platform. 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).
What's the best approach to do this? I feel like I need a @ConditionalOnCloudPlatform
annotation.
Thanks.
答案1
得分: 1
使用 @ConditionalOnMissingBean
与 Kubernetes bean 的名称,以及 @ConditionalOnMissingClass
与一个 bean(或相关类)的类之一。
英文:
Use @ ConditionalOnMissingBean
with the name of Kubernetes bean of @ ConditionalOnMissingClass
with one of bean's (or related) classes.
答案2
得分: 1
Solution 1
似乎您正在使用Spring Cloud Kubernetes
。如果是这样,当应用程序作为一个Pod在Kubernetes内部运行时,会自动激活名为'kubernetes'的Spring配置文件。
@Component
@Profile("!kubernetes")
public class MyLocalTestBean {}
Solution 2
使用NonNestedConditions反转条件(下面的代码未经验证)。
class ConditionalOnNotInCloud extends NoneNestedConditions {
ConditionalOnNotInCloud() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnCloudPlatform
static class OnCloudCondition {
}
}
@Bean
@Conditional(ConditionalOnNotInCloud.class)
public StubBean createStubBean() {}
英文:
Solution 1
It seems you are using Spring Cloud Kubernetes
. If so, when an application runs as a pod inside Kubernetes a Spring profile named 'kubernetes' is automatically get activated.
@Component
@Profile("!kubernetes")
public class MyLocalTestBean {}
Solution 2
Invert condition using NonNestedConditions (the code below is not verified)
class ConditionalOnNotInCloud extends NoneNestedConditions {
ConditionalOnNotInCloud() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnCloudPlatform
static class OnCloudCondition {
}
}
@Bean
@Conditional(ConditionalOnNotInCloud.class)
public StubBean createStubBean() {}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论