While working for the spring validation in our business tier, I came across two main areas which needed some work.
1. Move the hard-coded validation rules from source code to commons-validator xml files. This is easy but tedious job. Use xdoclet tags to define spring validation rules for java bean. Xdoclet will generate the validation xml from it.
2. Unlike web tier, spring will not automatically call the validator for business service arguments. In web tier, once we set validation property in the controller to true, validation is automatically enabled. That’s not the case with business tier. So instead of calling validator explicitly in the beginning of every business service method, I used MethodInterceptor to that job.
Writing method interceptor was easy. But invoking validator was a little trickier!
If you look at validator interfaces validate method signature, it seems like this:
void validate(Object obj, Errors errors)
Here “obj” is the object to be validated. But where should we get "errors" implementation? Use BeanException for it.
Documentation is pretty sparse on validation in business tier. After lot of playing around, I got this piece of code working:
public class ValidatorInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
Object[] args = methodInvocation.getArguments();
for (int i = 0; i <>
Object arg = args[i];
BeanException errors = new BeanException(arg, “arg”);
validator.validate(arg, errors);
if(errors.hasErrors()){
// do whatever you like
}
}
}
}
In the above code I am validating all the business service arguments.
For validator implementation, I used DefaultBeanValidator which is backed by commons-validator. You can use dependency injection in interceptor bean definition to set it.
For validation factory and validator bean definition, you have to download spring-validator jar from spring modules. Validation factory takes set of validation files as config locations. I specified validator-rules.xml and validation.xml for validation factory bean definition.
validator-rules.xml is the spring version of default validator file which comes packaged for struts validation rules. Other validation.xml is the custom validation rules file having application specific rules.
Let me know if you guys have any questions about this.