Enforce constraints on @Value annotated field in Spring Boot application

前端 未结 1 1885
北海茫月
北海茫月 2020-12-17 19:28

I have the following field annotated with @Value, specifying a default value:

@Value(\"${tolerance.percentage:25}\")
private int tolerance;


        
相关标签:
1条回答
  • 2020-12-17 20:00

    Validation using regular validation API annotations is only going to work in certain circumstances.

    1. You have an implementation ('hibernate-validator') on the classpath
    2. The class they are in are used to bind externalized configuration

    So instead of using @Value with those you probably want to create a class that contains the expected properties and use binding with @ConfigurationProperties. (and you might want to use @Range instead).

    @ConfigurationProperties(prefix="tolerance")
    public ToleranceProperties {
    
        @Range(min=1, max=100)
        private int percentage = 25; 
    
        // Here be a getter/setter
    }
    

    This combined on a @Configuration class add @ EnableConfigurationProperties(ToleranceProperties.class) and you can use it anywhere you need properties. (See typesafe configuration properties in the reference guide.

    Note: You could also declare it as a @Component.

    0 讨论(0)
提交回复
热议问题