在Spring Boot应用程序中对@Value带注释的字段施加约束 [英] Enforce constraints on @Value annotated field in Spring Boot application

查看:137
本文介绍了在Spring Boot应用程序中对@Value带注释的字段施加约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在以@Value注释的以下字段中指定了默认值:

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

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

如果该道具存在,则该代码将字段的值正确初始化为系统属性"tolerance.percentage".如果不存在,则默认为25.

That code correctly initializes the value of the field to the system property "tolerance.percentage" if that prop exists. If it doesn't exist, it defaults to 25.

不过,我想进一步加强此int字段的最小值和最大值,因为它表示一个整数百分比,小于100,而且墨菲定律意味着某人(可能是我)可以在外部错误地配置属性和我的应用程序将在运行时开始执行奇怪的操作,这对于我来说太晚了.如果在应用程序启动时将该属性设置为"101"或"-1",我希望抛出一个错误.哎呀,我什至希望在@Value批注中将其默认设置为101时引发错误,但这对于此问题而言并不重要.这是我尝试过的:

I want to go one step further, though, by enforcing a min and max on this int field, since it represents a percentage less than 100 as a whole number, and Murphy's law means someone (probably me) can externally misconfigure the property and my app would start doing weird things at runtime, which is way too late for my liking. I would like an error to be thrown if the property is set to "101" or "-1" upon application startup. Heck, I'd even like for an error to be thrown if I try to default it to 101 in the @Value annotation, but that's not important for the purposes of this question. Here's what I tried:

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

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

Can I enforce a min and max on an int field that @Value is aware of?

推荐答案

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

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

  1. 您在类路径上有一个实现("hibernate-validator")
  2. 它们所在的类用于绑定外部化配置

因此,您可能不想创建包含预期属性的类,并与@ConfigurationProperties绑定,而不是对它们使用@Value. (并且您可能想改用@Range).

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
}

这结合在@Configuration类上,添加了@ EnableConfigurationProperties(ToleranceProperties.class),您可以在需要属性的任何地方使用它. (请参见

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.

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

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

这篇关于在Spring Boot应用程序中对@Value带注释的字段施加约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆