title: JSR-303 validation is ignored when custom Validator is annotated with @Component
body: <p>I've noticed that JSR-303 validation is completely ignored in Spring when a custom Validator bean annotated with <code>@Component</code> is declared. Interestingly enough said custom validator doesn't even have to filled in or used by any of the classes. The fact that its component scanned by Spring appears to be enough to make Spring skip JSR-303 validation during object binding altogether. Removing <code>@Component</code> from custom Validator and restarting web application enables JSR-303 validation as expected. Annotating custom validators with <code>@Component</code> has its uses eg to have Spring Autowire dependencies.</p>
  <p>Consider simple example below:</p>
  <pre class="lang-java prettyprint-override"><code>/* Simple JSR-303 annotated User object */
  public class User {
      
      @NotNull @Size(min = 2, max = 5)
      protected String username;
      
      @Size(min = 2, max = 32)
      protected String firstName;
      
      @Size(min = 2, max = 32)
      protected String lastName;
      
      @NotNull @Past @DateTimeFormat(pattern=&quot;dd/MM/yyyy&quot;)
      protected Date dateOfBirth;
      
      @NotNull @Email
      protected String email;
      
      protected String phone;
      
      //getters and setters
  }
  </code></pre>
  <pre class="lang-java prettyprint-override"><code>/* Controller example */
  @RestController
  public class UserController {
      
      @PostMapping(&quot;/users/register&quot;)
      public ResponseEntity postUser(@Valid @RequestBody User user, BindingResult result) {
          if (result.hasErrors()) {
              return new ResponseEntity(result.getAllErrors(), HttpStatus.INTERNAL_SERVER_ERROR);
          }
          return new ResponseEntity(user, HttpStatus.CREATED);
      }
      
  }
  </code></pre>
  <pre class="lang-java prettyprint-override"><code>/* Custom validator (doesn't even have to be in use) */
  @Component //commenting out @Component annotation enables JSR-303 again
  public class SomeValidator implements Validator {
  
      @Override
      public boolean supports(Class&lt;?&gt; clazz) {
          //just an example
          return false;
      }
      
      @Override
      public void validate(Object target, Errors errors) {
          //empty
      }
  }
  </code></pre>
  <p>I was scratching my head over this one and couldn't figure out why my JSR-303 objects weren't validated but I managed to narrow it down and replicate this with a Spring Boot project containing above classes.
  Why is that? Am I missing something here or is this a Spring bug?</p>
  <hr />
  <h3>Edit</h3>
  <p><a href="https://github.com/BartoszKaszewczuk/JSR-303" rel="nofollow noreferrer">See demo Spring Boot project on GitHub</a></p>