Spring 启动 webflux - 验证配置属性

Spring boot webflux - Validating Configuration properties

我正在使用 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'

属性 Class

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 开箱即用验证支持?

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