在Spring Boot应用程序中对@Value注释字段强制实施约束

时间:2017-05-16 17:01:27

标签: java spring spring-boot

我有以下字段用@Value注释,指定默认值:

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

如果该prop支持存在,那么该代码正确地将字段的值初始化为系统属性“tolerance.percentage”。如果它不存在,则默认为25。

我想更进一步,通过在这个int字段上强制执行min和max,因为它代表一个小于100的百分比作为整数,而Murphy定律意味着有人(可能是我)可能从外部错误配置属性和我的应用程序将在运行时开始做奇怪的事情,这对我来说太迟了。如果在应用程序启动时将属性设置为“101”或“-1”,我想要抛出一个错误。哎呀,如果我试图在@Value注释中将其默认为101,我甚至会喜欢抛出错误,但这对于这个问题的目的并不重要。这是我试过的:

//@Min and @Max don't produce the intended behavior when combined with @Value
@Min(0)
@Max(100)
@Value("${tolerance.percentage:25}")
private int tolerance;

我可以在int知道的@Value字段上强制执行最小值和最大值吗?

1 个答案:

答案 0 :(得分:7)

使用常规验证API注释的验证仅在某些情况下才有效。

  1. 您在类路径
  2. 上有一个实现('hibernate-validator')
  3. 他们所在的班级用于绑定externalized configuration
  4. 因此,不要将@Value用于那些您可能想要创建包含预期属性的类并使用@ConfigurationProperties绑定的类。 (您可能希望使用@Range)。

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

    这组合在@Configuration类添加@ EnableConfigurationProperties(ToleranceProperties.class),您可以在任何需要属性的地方使用它。 (参见参考指南中的typesafe configuration properties

    注意:您也可以将其声明为@Component