I have a Spring Boot app that contains an User class - all fields have standard JSR-303 annotations (@NotNull, @Size, etc.) and validation works fine.
However when I add a custom validation to User, I can't get a dependency injected into a custom validator:
@Component
public class UniqueUsernameValidator implements
ConstraintValidator<UniqueUsername, String> {
@Autowired
private UserRepository userRepository;
@Override
public boolean isValid(String username, ConstraintValidatorContext context) {
// implements logic
}
@UniqueUsername annotation is declared as:
@Documented
@Retention(RUNTIME)
@Target({FIELD, ANNOTATION_TYPE, PARAMETER})
@Constraint(validatedBy = UniqueUsernameValidator.class)
@interface UniqueUsername {
String message() default "{com.domain.user.nonUniqueUsername}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
The annotated field:
@NotBlank
@Size(min = 2, max = 30)
@UniqueUsername
private String username;
And the validator usage:
@Service
public final class UserService {
private final UserRepository userRepository;
private final Validator validator;
public UserService(UserRepository userRepository, Validator validator)
{
this.userRepository = userRepository;
this.validator = validator;
}
public void createUser(User user) {
Set<ConstraintViolation<User>> validate = validator.validate(user);
// logic...
}
}
The problem is that UserRepository is not being autowired in UniqueUsernameValidator. Field is always null.
I am using a LocalValidatorFactoryBean.
Does anyone have any idea why autowiring's not working?
@Controller
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping("/user/new")
public String createUser(@ModelAttribute("newUser") User newUser, BindingResult bindingResult,
Model model) {
userService.createUser(newUser);
// omitted
}
@Valid
or@Validated
annotation in your sample. Who and where is doing the validation? – JenneeLocalValidatorFactoryBean
present in your Spring Configuration ? – Constellation