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

时间:2015-06-26 09:07:52

标签: java hibernate-validator

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

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

这很好,但我可以动态更改min和max的值而不是硬编码。我的意思是我可以这样做:

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

2 个答案:

答案 0 :(得分:4)

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

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

如果您想让它可配置,您可以将它们声明为静态最终版。

例如:

private static final int MIN_RANGE = 1;

private static final int MAX_RANGE = 100;

然后在注释中分配。

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

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

答案 1 :(得分:1)

If you are using Spring in your project, you can do something like this:

properties file:

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;

It's not dymanic change, but i think you trying to find something like this