I keep getting validator error for quite simple configuration class
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotBlank;
@Component
@Data
@Validated
@ConfigurationProperties(prefix = "test")
public class TestProperties {
@NotBlank
String uri;
}
Error is self explaining:
javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.NotBlank' validating type 'java.lang.String'. Check configuration for 'uri'
But according to spring boot documentation this should work.
Annotation Type NotBlankDeprecated. Validate that the annotated string is not null or empty. The difference to NotEmpty is that trailing whitespaces are getting ignored.
@NotEmpty: a constrained CharSequence, Collection, Map, or Array is valid as long as it's not null, and its size/length is greater than zero. @NotBlank: a constrained String is valid as long as it's not null, and the trimmed length is greater than zero.
The @Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graph. However, this creates issues for scenarios needing only partial validation. On the other hand, we can use @Validated for group validation, including the above partial validation.
The @NotNull annotation is, actually, an explicit contract declaring that: A method should not return null. Variables (fields, local variables, and parameters) cannot hold a null value.
I had the same issue and solved it.
As Yogi stated in his answer, there are two implementations:
import javax.validation.constraints.NotBlank;
and
import org.hibernate.validator.constraints.NotBlank;
Switching from the javax
implementation to the hibernate
one solved the issue.
Since I didn't use Spring boot, I had to add to my pom.xml:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
According to Spring-Boot documentation and maven central repo the:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
has the validator included. If you have not spring-boot-starter-web included to your dependencies you can just add the validator:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With