Setting dynamic data for minimum and maximum attributes of @Range annotation - sleep mode validators

Iam using the Hibernate Validator to validate data. I used the @Range attribute to validate a specific field.

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

This is great, but I can dynamically change the min and max values ​​instead of hard coding. I mean, can I do something like:

 @Range(min=${},max=${}) private String amount; 
+5
source share
2 answers

Annotations in Java use constants as parameters. You cannot change them dynamically.

Compilation constants can only be primitives and strings. Check out this link.

IF you want to configure it, you can declare them as static final.

Example:

 private static final int MIN_RANGE = 1; private static final int MAX_RANGE = 100; 

and then assign in annotations.

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

The value of the annotation attribute must be a constant expression.

+4
source

If you use 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; 

This is not a diminutive change, but I think you are trying to find something like this

0
source

All Articles