Hello I have the next piece of code:
@Setter
@Getter
@Builder
public class User {
@Pattern(regexp = "[a-zA-Z]*")
private String username;
public User(String username){
this.username = username;
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Set<ConstraintValidation<User>> violations = factory.getValidator().validate(this);
if(!violations.isEmpty) throw new ConstraintViolationExcetion(violations);
}
It is working, and when I try to create an User it always check the constraints (also with builder pattern), but i would like to avoid to generate the constructor and use the lombok anotation @AllArgsConstructor and use the PostConstruct from javax to validate.
@Setter
@Getter
@AllArgsConstructor
@Builder
public class User {
@Pattern(regexp = "[a-zA-Z]*")
private String username;
@PostConstruct
public void valid() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Set<ConstraintValidation<User>> violations = factory.getValidator().validate(this);
if(!violations.isEmpty) throw new ConstraintViolationExcetion(violations);
}
I'm using JAVA11 including javax.annotation dependency. User is a regular object, not a bean of spring. But this way is not working... How can I make it work? Thanks.