春季引导 – 使用自定义 yml 标签扩展 yml 配置

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

Spring Boot - extend yml configuration with custom yml tags

问题

我需要在Spring Boot应用程序的application.yml中同时使用YAML锚点引用和字符串连接。动机是为了重用现有的配置,避免重复。例如,我们有以下的application.yml配置:

sources:
  - filter:
      expression: &mainFilter
                    level > 100
  - filter:
      expression: *mainFilter
  - filter:
      expression: *mainFilter and level < 200

我需要使其解析为以下内容:

sources:
  - filter:
      expression: &mainFilter
                    level > 100
  - filter:
      expression: level > 100
  - filter:
      expression: level > 100 and level < 200

expression: *mainFilter 会被正确解析,因为它是YAML锚点,但是 expression: *mainFilter and level < 200 无法工作,因为YAML不支持带有连接的锚点(应用程序将在启动时失败)。根据 yml string concatenation with custom tags 的说法,YAML 有类似自定义标签的概念,我们可以定义类似 expression: !concat [*mainFilter, 'and level < 200'] 这样的标签。在 Spring Boot 的 YAML 配置中是否可以定义并注册我们自己的自定义标签呢?

英文:

I need to use yaml anchor references together with string concatenation inside application.yml for Spring Boot app. Motivation is to reuse existing configs and not duplicate them.
For example, we have the following application.yml:

sources:
  - filter:
      expression: &mainFilter
                    level > 100
  - filter:
      expression: *mainFilter
  - filter:
      expression: *mainFilter and level < 200

I need that it will be resolved to the following:

sources:
  - filter:
      expression: &mainFilter
                    level > 100
  - filter:
      expression: level > 100
  - filter:
      expression: level > 100 and level < 200

expression: *mainFilter will be resolved correctly as it's yml anchors, but expression: *mainFilter and level < 200 will not work as yml doesn't support anchors with concatenation (app will fail on app start). According to yml string concatenation with custom tags, yml has notion as custom tags that we could define, like expression: !concat [*mainFilter, 'and level < 200']. Is it possible to define and register our own custom tags in Spring Boot yml configuration?

答案1

得分: 1

我有同样的需求——从现有的属性值中组合出新的属性值——起初我像你一样认为这需要自定义标签,在 Spring 中,你可以使用 属性占位符 来实现:

mainFilter: "level > 100"
sources:
  - filter:
      expression: ${mainFilter}
  - filter:
      expression: "${mainFilter} and level < 200"
英文:

I had the same need -- composing new property values from existing property values -- and after first thinking like you that it requires custom tags, in spring you can use property placeholders instead:

mainFilter: "level > 100"
sources:
  - filter:
      expression: ${mainFilter}
  - filter:
      expression: "${mainFilter} and level < 200"

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

发表评论

匿名网友

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

确定