title: How to re-use Hibernate Validation with custom validators in both Spring MVC and API layer
body: <p>Lets say that i have an application that front-end is built using Spring MVC.
  That same application exposes API for integration purposes.</p>
  
  <p>Errors in Web are shown by using Spring MVC form:error tags by using JSR-303 and Hibernate validator with custom constraints. </p>
  
  <p>Everything is fine, but i want to reuse the same validation in my API layer, and fail with error codes if my validation fails.</p>
  
  <p>Lets say i have a POJO object (just an example):</p>
  
  <pre><code>@ValidDomainObject
  public class DomainObject {
  
      public String superSetting;
  
      public String anotherSetting;
  
      public String getSuperSetting() {
          return superSetting;
      }
  
      public void setSuperSetting(String superSetting) {
          this.superSetting = superSetting;
      }
  
      public String getAnotherSetting() {
          return anotherSetting;
      }
  
      public void setAnotherSetting(String anotherSetting) {
          this.anotherSetting = anotherSetting;
      }
  
  }
  </code></pre>
  
  <p>And @ValidDomainObject is validated by this Validator:</p>
  
  <pre><code>public class DomainObjectValidator implements ConstraintValidator&lt;ValidDomainObject, DomainObject&gt; {
  
      @Override
      public void initialize(final ValidDomainObject constraintAnnotation) {
  
      }
  
      @Override
      public boolean isValid(final DomainObject obj, final ConstraintValidatorContext context) {
          context.disableDefaultConstraintViolation();
          if (obj.getAnotherSetting().equals(obj.getSuperSetting())) {
              context
                      .buildConstraintViolationWithTemplate("{message.to.show}")
                      .addConstraintViolation();
          }
      }
  }
  </code></pre>
  
  <p>All is fine in the front MVC tier - i define message.to.show in language files to resolve to something like "Cannot set X to Y" and user sees the message on the page.</p>
  
  <p>So how do i achieve same thing in the API layer? If i want to throw ServiceFault with ErrorCodes.PROPERTIES_MATCH or similar ?</p>
  
  <p>I could simply use:</p>
  
  <pre><code>   Set&lt;ConstraintViolation&lt;DomainObject&gt;&gt; validationErrors = validator.validate(domainObject);
  </code></pre>
  
  <p>And then loop the retrieved set checking for messages and building faults with given error codes. But that seems like front-end coupling with API  layer.</p>
  
  <p>I could do vice versa:</p>
  
  <pre><code>      context.buildConstraintViolationWithTemplate(
  ErrorCodes.PROPERTIES_MATCH.toString()) .addConstraintViolation();
  </code></pre>
  
  <p>But then, the message structure for front end is not as the other messages, and no interpolation.</p>
  
  <p>What would be the best approach ?</p>