title: Autowiring a service into a validator
body: <p>This example is a bit contrived; I've simplified it to remove extraneous details and to focus on the problem I am having. I have a validator that looks like this:</p>
  
  <pre><code>@Component
  public class UniqueUsernameValidator implements ConstraintValidator&lt;UniqueUsername, String&gt; {
  
      @Autowired
      UsernameService usernameService;
  
      @Override
      public void initialize(UniqueUsername uniqueUsername) {
      }
  
      @Override
      public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
          return !usernameService.exists(s);
      }   
  }
  </code></pre>
  
  <p>I call the validator from my controller like this:</p>
  
  <pre><code>@RequestMapping
  public void checkUsername(Model model, User user) {
      ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
      Validator validator = factory.getValidator();
  
      Set&lt;ConstraintViolation&lt;User&gt;&gt; constraintViolations = validator.validateProperty(user, "username");
      model.addAttribute("error", constraintViolations.size() &gt; 0);
  }
  </code></pre>
  
  <p>However, I keep getting an <code>NullPointerException</code> exception. I added a breakpoint in my validator and saw that <code>usernameService</code> was <code>null</code>. Why isn't it getting autowired? Initially I thought it was because I hadn't annotated the validator with <code>@Component</code>, but I still have the same problem even after annotating it. The <code>UsernameService</code> class has already been annotated with <code>@Service</code> and I can verify that its constructor is getting called.</p>
  
  <p>I am new to Spring, so I'm not even sure if it is alright to wire a service into a validator. What am I doing wrong?</p>