【问题标题】:Spring boot webflux - Validating Configuration propertiesSpring Boot webflux - 验证配置属性
【发布时间】:2021-05-10 21:02:17
【问题描述】:

我正在使用 Spring Boot webflux 2.4.2。

build.gradle

implementation 'org.springframework.boot:spring-boot-starter-validation'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.boot:spring-boot-starter-data-r2dbc'
    implementation 'org.springframework.boot:spring-boot-starter-webflux'

属性类

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;


    @Validated
    @ConfigurationProperties(prefix = "service")
    public class AppProperties {
    
        private String env;
        
        public String getEnvrironment() {
          return envrironment;
        }

        public void setEnvrironment(String envrironment) {
           this.envrironment = envrironment;
        }
    }


public enum Environments {
    
    DEV,
    UAT,
    PROD

}

application.properties

service.environment=DEV

在这里,我想将环境属性验证为枚举值之一。是否有针对此用例的 Spring Boot 开箱即用验证支持?

【问题讨论】:

    标签: spring-boot spring-validator


    【解决方案1】:

    Spring Boot 可以为您直接绑定到一个枚举。如果您将AppProperties env 字段的类型更改为Environments,Spring Boot 将自动强制service.environment 属性的值是Environments 枚举中声明的三个值之一。它还支持不区分大小写的绑定,因此您可以配置service.environment=dev,并将AppProperties'env 字段的值设置为Environments.DEV

    【讨论】:

      猜你喜欢
      • 2020-12-10
      • 2017-09-15
      • 2019-05-19
      • 2020-06-14
      • 2022-01-19
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      • 2018-01-29
      相关资源
      最近更新 更多