使用Spring Boot 2.2+,当应用程序未在云平台上运行时,如何创建一个Bean。

huangapple go评论79阅读模式
英文:

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() {}

huangapple
  • 本文由 发表于 2020年7月28日 10:44:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/63126287.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定