oxyt oxyt - 2 months ago 41
Java Question

Spring Validator: Could not autowire. No beans of 'Validator' type found

I don't know if I need to and some more code/details about this but I am ready to supply more info if needed :)

I get:

Could not autowire. No beans of 'Validator' type found
. There are similar questions in here but there are not about
Validator
. I tried to autowire it via constructor but it is still same. I use Intellij Ultime edition. Latest version of
spring-boot-starter-xxx-xxx
which is 1.4.1.RELEASE at the moment.

@Configuration
public class RestConfig extends RepositoryRestConfigurerAdapter {

@Autowired
private Validator validator;

@Override
public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) {
validatingListener.addValidator("beforeCreate", validator);
validatingListener.addValidator("beforeSave", validator);
}
}


Edit:

I changed my code to this and it worked. Thanks for answers..

@Bean
public Validator validator() {
return new LocalValidatorFactoryBean();
}


@Override
public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) {
validatingListener.addValidator("beforeCreate", validator());
validatingListener.addValidator("beforeSave", validator());
}


By the way, I just wonder if the person who voted down this question can explain why he/she did that?

Answer

The Spring library just contains an interface for Validator. You need to add a dependency to your project that actually implements the Validation framework JSR-303 like Hibernate Validator.