0

I have a composite bean which includes inner beans and some of these inner beans also have inner beans. This composite bean have total 200+ properties (properties of this bean + properties of inner beans). I am using JSR 303 for validating user inputs. My requirements suggest to go for cross field bean validations.

I have went through few blogs and suggestions like http://dwuysan.wordpress.com/2012/03/20/cross-field-validation-using-bean-validation-jsr-303/ , regarding the same. Similar kind of explanation can be found here: Cross field validation with Hibernate Validator (JSR 303).

Both suggest same approach for defining class level constraints for cross-field validation. Their approach is uses BeanUtils.getProperty() method which in turn uses Java Reflections on runtime while performing bean validation.

I want to know that is it good to define JSR 303 corss-field contrains using reflections which evaluate at runtime (performance degradation) or go for other validation strategies like Spring Validation or Service layer validation by custom methods?

Community
  • 1
  • 1
Vaibhav Raj
  • 2,214
  • 4
  • 23
  • 39

1 Answers1

1

If your requirement is just to implement a few cross-field validation rules, I'd recommend to implement dedicated class-level constraints which access the concerned properties by simply calling their getters. This makes the constraint type-save and it avoids reflection.

If you have lots of cross-field validations which make creating dedicated constraints for all of them a tedious task, a generic approach like @FieldMatch might save some work. I think the overhead for reflection should be neglectable in most cases. If you see a performance downgrade, you could still implement specific class-level constraints for the most-critical cases.

Gunnar
  • 18,095
  • 1
  • 53
  • 73
  • 1
    As I know about JSR 303 that an annotation has only visibility of the field on which it is applied (without using reflections). How to use getters and setters to achieve this kind of validation? Can you elaborate more? – Vaibhav Raj Jun 17 '13 at 10:17
  • 1
    You can apply constraints not only to properties/fields but also the the entire class (class-level constraint). The validator of such a constraint gets passed the complete bean to its `isValid()` method and thus can access all its properties. See the Hibernate Validator [reference guide](http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-class-level-constraints) for more details. – Gunnar Jun 17 '13 at 12:25