Spring Ch 2. 추상화 - Validation 추상화


Validation

  • 객체를 검증하기 위해 사용되는 인터페이스.
  • 웹, 서비스 등 모든 계층에 관계가 없어 일반적으로 사용할 수 있다는 장점이 있다.
  • Bean Validation의 Annotation으로 객체의 데이터를 검증할 수 있다.
  • Validator는 기본적으로 다음 두 함수를 오버라이드하여 검증해야한다.
    • boolean supports(class<?>) - 검증할 객체의 타입을 체크하는 함수.
    • void validate(Object, Errors) - 실제 검증이 이루어지는 함수.
1
2
3
4
5
6
7
8
9
10
11
12
public class EventValidatior implements Validator{
@Override
public boolean supports(Class<?> clazz) {
return Event.class.equals(clazz);
}

@Override
public void validate(Object target, Errors errors) {
//title 필드 값이 비어있는지 검증한다.
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title","notempty","default message");
}
}

어노테이션을 사용한 객체 검증

  • Spring Boot 2.0.5 이상의 버전에서는 @Autowired 어노테이션으로 LocalValidatorFactoryBean을 자동으로 등록할 수 있다.
  • @NotEmpty, @Min, @Email과 같은 어노테이션만으로도 객체 검증을 등록할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Event {
@Max(1000)
Integer id;

@NotEmpty
String title;

@Min(0)
Integer limit;

@Email @NotNull
String email;
}
  • 애플리케이션에서 Validator 객체를 주입받아 validate함수를 호출하면 어노테이션으로 정의된 Validation을 체크한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
   @Autowired
Validator validator;

@Override
public void run(ApplicationArguments args) throws Exception{
System.out.println(validator.getClass());

Event event = new Event();
event.setLimit(-1);
event.setEmail("aaa");
Errors errors = new BeanPropertyBindingResult(event, "event");

validator.validate(event, errors);
errors.getAllErrors().forEach(e->{
System.out.println("========error code========");
Arrays.stream(e.getCodes()).forEach(System.out::println);
System.out.println(e.getDefaultMessage());
});
}
  • Spring 3 이상의 버전에서는 Validation이 기본 Dependency로 포함되어있지 않다. 다음과 같이 의존성을 추가해야한다.
1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

댓글