将动态数据设置为 @Range 注释的最小和最大属性 - hibernate 验证器

Setting dynamic data to min and max attributes of @Range annotation - hibernate validators

我正在使用 Hibernate Validator 来验证数据。我使用@Range 属性来验证特定字段。

@Range(min=0,max=100)
private String amount;

很好,但是我可以动态更改最小值和最大值而不是硬编码吗?我的意思是我可以做类似的事情吗:

@Range(min=${},max=${})
private String amount;

Java 中的注释使用常量作为参数。您不能动态更改它们。

编译常量只能是原语和Strings.Check这个link

如果你想让它可配置,你可以将它们声明为 static final。

例如:

private static final int MIN_RANGE = 1;

private static final int MAX_RANGE = 100;

然后在注解中赋值

@Range(min=MIN_RANGE,max=MAX_RANGE)
private String amount;

注释属性的值必须是常量表达式。

如果您在项目中使用 Spring,您可以这样做:

属性文件:

min_range = 0
max_range = 100

spring.xml:

<context:component-scan
    base-package="com.test.config" />
<context:annotation-config />

<bean id="appConfigProperties"    class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="location" value="classpath:appconfig.properties" />
</bean>

java:

@Range(min=${min_range},max=${max_range})
private String amount;

这不是动态变化,但我认为你正试图找到类似这样的东西