So. I'm trying to have a custom validator for my method. This one:
@PostMapping("/person")
public Person create(@Validated(value = IPersonValidator.class) @RequestBody Person person, Errors errors) {
LOGGER.info("Creating a person with the following fields: ");
LOGGER.info(person.toString());
if (errors.hasErrors()) {
LOGGER.info("ERROR. Error creating the person!!");
return null;
}
//return personService.create(person);
return null;
}
This is my Validator class:
@Component
public class PersonValidator implements Validator, IPersonValidator {
@Override
public boolean supports(Class<?> clazz) {
return Person.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
Person person = (Person) target;
if (person.getName() == null || person.getName().trim().isEmpty()) {
errors.reject("name.empty", "null or empty");
}
}
}
And my interface:
public interface IPersonValidator {
}
And my class:
@Entity
@Table(name = "persons")
@Data
@Getter
@Setter
@NoArgsConstructor
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "person_sequence")
@SequenceGenerator(name = "person_sequence", sequenceName = "person_sequence", allocationSize = 1)
@Column(name = "id")
private Long id;
//@NotBlank(message = "Name cannot be null or empty")
@Column(name = "name")
private String name;
@NotBlank(message = "Lastname cannot be null or empty")
@Column(name = "last_name")
private String lastName;
@Column(name = "last_name_2")
private String lastName2;
public Person(String name, String lastName, String lastName2) {
this.name = name;
this.lastName = lastName;
this.lastName2 = lastName2;
}
}
What am I expecting is for it to enter the validate method since Im using the annotation (@Validate) with the class that I want. I tried it too using the @Valid annotation, but it still won't enter in my custom validate method.
What am I doing wrong?