我使用 JSR-303 bean 验证和 Spring 3,我需要根据用例为注释提供不同的值。
例如,值min
参数输入@Size(min=?)
对于某些验证必须为 1,对于另一种情况必须为 5,我想从属性文件中读取此值。
我知道可以从中读取消息参数ValidationMessages.properties
文件如果作为键提供,但其他参数呢?
正如 dpb 所概述的,您可以使用验证组 http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html/validator-usingvalidator.html#validator-usingvalidator-validationgroups使用不同的属性值指定相同的约束。
如果您正在与休眠验证器 http://validator.hibernate.org作为 BV 实现,基于此您可以使用编程式API http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html/validator-specifics.html#programmaticapi而不是用注释来定义您的约束。这样您就可以在运行时检索具体的约束值,如下所示:
int minValue1 = ...; //read from properties file etc.
int minValue2 = ...;
//programmatically define the constraints for the Test type
ConstraintMapping mapping = new ConstraintMapping();
mapping.type( Test.class )
.property( "prop", FIELD )
.constraint( new NotNullDef() )
.constraint( new SizeDef().min( minValue1 ).groups( GroupOne.class ) )
.constraint( new SizeDef().min( minValue2 ).groups( GroupTwo.class ) );
//retrieve a validator using the programmatic constraint mapping
HibernateValidatorConfiguration config =
Validation.byProvider( HibernateValidator.class ).configure();
config.addMapping( mapping );
ValidatorFactory factory = config.buildValidatorFactory();
Validator validator = factory.getValidator();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)