title: Spring Boot - Hibernate custom constraint doesn't inject Service
body: <p>I will try to ignore other details and make it short:</p>
  
  <pre><code>@Entity
  public class User
      @UniqueEmail
      @Column(unique = true)
      private String email;
  }
  
  @Component
  public class UniqueEmailValidatior implements ConstraintValidator&lt;UniqueEmail,String&gt;, InitializingBean {
  
      @Autowired private UserService userService;
  
      @Override
      public void initialize(UniqueEmail constraintAnnotation) {
  
      }
  
      @Override
      public boolean isValid(String value, ConstraintValidatorContext context) {
          if(userService == null) throw new IllegalStateException();
          if(value == null) return false;
          return !userService.isEmailExisted(value);
      }
  
  }
  </code></pre>
  
  <p>This will work when the validation is made in Spring (Spring MVC <code>@Valid</code> or  inject the <code>Validator</code> using <code>@Autowire</code>), everything will be fine. 
  But as soon as I save the entity using Spring Data JPA:</p>
  
  <pre><code>User save = userRepository.save(newUser);
  </code></pre>
  
  <p>Hibernate will try to instantiate a new <code>UniqueEmailValidatior</code> without inject the <code>UserService</code> bean.
  So how can I make Hibernate to use my <code>UniqueEmailValidatior</code> component without it instantiate a new one.
  I could disable hibernate validation using <code>spring.jpa.properties.javax.persistence.validation.mode=none</code> but I hope there is another way</p>
  
  <p>Update: Here is my UserService:</p>
  
  <pre><code>   @Autowired private Validator validator;
     @Transactional
      public SimpleUserDTO newUser(UserRegisterDTO user) {
          validator.validate(user);
          System.out.println("This passes");
          User newUser = new User(user.getUsername(),
                  passwordEncoder.encode(user.getPassword()),user.getEmail(),
                  "USER",
                  user.getAvatar());
          User save = userRepository.save(newUser);
          System.out.println("This won't pass");
          return ....
      }
  </code></pre>