Spring @Value注释强制执行min max int [英] Spring @Value annotation enforce min max int

查看:1589
本文介绍了Spring @Value注释强制执行min max int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字段用 @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字段强制执行min和max,因为它代表一个小于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;

我可以在 int @Value 的字段是否知道?

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. 他们上课了in in用于绑定外化配置

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

所以不要使用 @Value 可能想要创建一个包含预期属性的类,并使用 @ConfigurationProperties 绑定。 (你可能想要使用 @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),你可以在任何需要的地方使用它。 (参见 typesafe配置属性

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 @Value注释强制执行min max int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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