title: Spring (Boot) validation annotations for different layers on the same class
body: <p>Given a web application with <em>Spring Boot</em>, <em>Spring MVC</em> and <em>Spring Data</em> (with <em>MongoDB</em> as a database) and a one class used to represent request  on multiple layers (REST, service, persistence).</p>
  
  <p>Is it possible to declarative specify validation constraints on the fields of the class such that some of them would apply only for certain layers (or will be ignored by some) ?</p>
  
  <p>Example:</p>
  
  <p><strong>Entity</strong> (getter and setter autogenerated)</p>
  
  <pre><code> public class User {
  
       private String name;
  
       @NotEmpty
       private String role;
   }
  </code></pre>
  
  <p>where <code>@NotEmpty</code> is <em>JSR 303</em> anotation</p>
  
  <p><strong>REST API layer</strong></p>
  
  <p><code>role</code> does not exist here</p>
  
  <pre><code>@RestController
  public class RegisterController {
  
      @Autowired
      private UserService service;
  
      @PostMapping
      public User register(@Valid User u) {
          return service.createAppUser(u);
      }
  }
  </code></pre>
  
  <p><strong>Service layer</strong> </p>
  
  <p><code>role</code> is set by the implementation and is required by the persistence layer</p>
  
  <pre><code>@Service
  public class UserService {
  
      @Autowired
      private UserRepo repo;
  
      private User createAppUser(User u) {
          u.setRole("APP_USER");
          return repo.save(u);
      }
  }
  </code></pre>
  
  <p>where <code>repo</code> is <em>Spring Data</em> <code>MongoRepository</code>.</p>
  
  <p>I can think of two approaches which solve this:</p>
  
  <ol>
  <li>Introduce DTO object for REST API layer</li>
  <li>Manual/ procedural validation; either using <em>Spring</em> <code>Validator</code> or something else, doesn't matter - simply nothing declarative</li>
  </ol>
  
  <p>Both of which I don't like very much as they require lot of boilerplate and this is a trivial case.</p>