I am working on an app using spring boot for the backend and vaadin for the frontend. I need to add validation, which needs to do a database check - is email registered in this particular example.
Example of what i want to achieve:
@Component
public class EmailExistsValidator implements ConstraintValidator<EmailExists, CharSequence> {
private final UserRepo userRepo;
@Autowired
public EmailExistsValidator(UserRepo userRepo) {
this.userRepo = userRepo;
}
@Override
public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
//check email does not exist logic here
}
}
I have successfuly used this setup in spring mvc and spring rest applications, with no additional configurations. Unfortunately, the above is not working with vaadin. After some debugging i found out that spring indeed creates and manages those components, but they are not the ones being used. Instead vaadin creates and manages other instances of ConstraintValidator, when the actual validation is happening. The validation is done with Binder.writeBeanIfValid(), if that matters.
I went through:
- Autowired Repository is Null in Custom Constraint Validator
- Spring Boot: repository does not autowire in the custom validator
- All questions linked in the above as possible solutions
- Few more questions, which i can no longer find unfortunately
- I tried getting
WebApplicationContext
in order to useAutowireCapableBeanFactory.autowireBean()
to autowire the annotated fields. Unsurprisingly, the context wasnull
when vaadin creates/manages the instance, so it did not work.
What i am currently using.
@Component
public class EmailExistsValidator implements ConstraintValidator<EmailExists, CharSequence> {
private static UserRepo repo;
private final UserRepo userRepo;
public EmailExistsValidator() {
this.userRepo = repo;
}
@Bean
public static UserRepo setRepo(UserRepo userRepo) {
repo = userRepo;
return repo;
}
@Override
public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
//validation logic
}
}
This approach is based on this answer (from the second question i linked). It does the job (only this worked for me), but it's way too hacky for my tastes.
How can I configure vaadin to use spring managed ConstraintValidator
s, instead of vaadin managed ones? Or how can I autowire spring components in ConstraintValidator
s created and managed by vaadin?