如果kotlin spring boot应用程序中存在配置组合,如何使其失败';s.yaml

如果kotlin spring boot应用程序中存在配置组合,如何使其失败';s.yaml,spring,spring-boot,kotlin,spring-cloud-gateway,spring-properties,Spring,Spring Boot,Kotlin,Spring Cloud Gateway,Spring Properties,我有一个微服务,它是kotlin的spring云网关实现。 因此,作为功能的一部分,如果我在application.yaml中的过滤器配置中发现了参数的特定组合,我需要启动此服务失败。 为了给出过滤器的联合配置,我们使用内联表示法。 例如: spring: cloud: gateway: routes: - id: test1 predicates: - Path=/test1/** fil

我有一个微服务,它是kotlin的spring云网关实现。 因此,作为功能的一部分,如果我在application.yaml中的过滤器配置中发现了参数的特定组合,我需要启动此服务失败。 为了给出过滤器的联合配置,我们使用内联表示法。 例如:

 spring:
  cloud:
    gateway:
      routes:
        - id: test1
          predicates:
            - Path=/test1/**
          filters:
            - RewritePath=/test1/(?<segment>.*), /$\{segment}
            - TLS= OPTIONAL, NONE, TEST
        - id: test2
          predicates:
            - Path=/test2/**
          filters:
            - RewritePath=/test2/(?<segment>.*), /$\{segment}
            - TLS= MANDATORY, NONE, TEST
spring:
云:
网关:
路线:
-id:test1
谓词:
-路径=/test1/**
过滤器:
-重写路径=/test1/(?*),/$\{segment}
-TLS=可选,无,测试
-id:test2
谓词:
-路径=/test2/**
过滤器:
-重写路径=/test2/(?*),/$\{segment}
-TLS=强制性,无,测试
因此,在这个示例配置中,TLS筛选器将ags组合设为强制组合,但没有,在这种情况下,该服务应该在开始时失败,并说“强制组合,但没有是正确的组合”


因此,任何实现这一点的建议???

实现这一点的一种方法是创建一个ApplicationEventListener。基本上,您可以注册其中一个侦听器来侦听Spring启动事件:(其中一个:)


您可以在这里看到一个示例实现:
https://stackoverflow.com/questions/56372260/spring-load-application-properties-in-application-listener
。在该示例中,正在加载属性。在您的情况下,我设想您可以检查您感兴趣的属性,如果有任何内容违反您的要求,则抛出RuntimeException。

我在kotlin中找到了另一种方法。 在类中使用init块。

TLSFilter代码,如果在该筛选器的路由中找到特定组合,则该代码将失败

class TLSFilter(
    private val filterProperties: TLSFilterProperties,) : GatewayFilter {

private val logger = logger()

init {
    if (filterProperties.mode == DISABLE && (filterProperties.type?.isNotEmpty() == true)) {
        throw IllegalStateException("Security mode `DISABLE` should not be present with any security type in filter configuration.")
    }
    
    if ((filterProperties.mode == MANDATORY || filterProperties.mode == OPTIONAL) && filterProperties.type?.equals(NONE.name) == true) {
        throw IllegalStateException("Security mode = ${filterProperties.mode} with security type = NONE is not a valid configuration.")
    }
}}
TLSFilterProperties类,该类自动与spring cloud gateway应用程序的application.yml文件绑定

  /**
 * Properties that should be initialized in filter configuration properties
 */
class TLSFilterProperties {

    lateinit var mode: SecurityMode
    var type: String? = null
    var alias: String? = null

    companion object {

        val configFieldsOrder = listOf(
                "mode",
                "type",
                "alias"
        )
    }
}
谢谢亚历克斯的回答:)但我用另一种方式解决了这个问题。