본문 바로가기
Java, Kotlin, Spring/Spring, Spring Boot

Spring - Validation

by Wordbe 2021. 1. 12.
728x90

Validation 추상화

 

org.springframework.validation.Validator

주로 spring MVC 에서 사용하지만, 웹 MVC 전용은 아니다. 애플리케이션에서 사용하는 객체 검증을 위한 일반적 인터페이스이다.

예제를 만들기 위해 이벤트를 하나 생성한다.


  
@Getter
@Setter
public class RedEvent {
Integer id;
String title;
}

(lombok 을 사용하여 자동 게터, 세터를 생성한다고 하자)

 

이제 위 이벤트를 가지고 Validator 를 구현해보자.

Validator를 사용하려면 두 가지 메소드를 구현해야 한다.

supports, validate


  
public class RedEventValidator implements Validator {
@Override
public boolean supports(Class<?> aClass) {
return RedEvent.class.equals(aClass);
}
@Override
public void validate(Object o, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title", "notempty", "제목이 있어야 합니다.");
}
}

 

애플리케이션 러너에 이벤트와 에러를 등록한 후 validate() 메소드를 사용해보자.


  
@Component
public class AppRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
// event 설정
RedEvent event = new RedEvent();
// error 설정
// BeanPropertyBindingResult 는 spring MVC 가 직접 만들어준다.
Errors errors = new BeanPropertyBindingResult(event, "event");
RedEventValidator eventValidator = new RedEventValidator();
eventValidator.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());
});
}
}
}

title 이 없을 때 에러가 발생하는 것을 보여준다.

 

 


Springboot 에서 이를 더 쉽게 이용해보자.

springboot 2.3 버전 이후 부터는 validation 을 따로 등록해야 한다.

pom.xml (maven)


  
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

build.gradle (gradle)


  
depedencies {
...
implementation 'org.springframework.boot:spring-boot-starter-validation'
}

 

 

이벤트에 아래와 같은 필드를 등록시키고 애노테이션을 넣어서 검증 조건을 추가해주자.

@NotEmpty, @NonNull 등의 애노테이션을 위해 spring-boot-starter-validation 의존성이 필요하다.


  
@Getter
@Setter
public class RedEvent {
Integer id;
@NotEmpty
String title;
@NotNull @Min(0)
Integer limit;
@Email
String email;
}

 

 

 


  
@Component
public class AppRunner implements ApplicationRunner {
@Autowired
Validator validator;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println(validator.getClass());
// event 설정
RedEvent event = new RedEvent();
event.setLimit(-1);
event.setEmail("abc32®");
// error 설정
Errors errors = new BeanPropertyBindingResult(event, "event");
validator.validate(event, errors);
System.out.println(errors.hasErrors());
errors.getAllErrors().forEach(e -> {
System.out.println("-------- error code --------");
Arrays.stream(e.getCodes()).forEach(System.out::println);
System.out.println(e.getDefaultMessage());
});
}
}

세가지 에러가 출력되는 것을 확인할 수 있다.

728x90

'Java, Kotlin, Spring > Spring, Spring Boot' 카테고리의 다른 글

Spring - spEL(스프링 Expression Language)  (4) 2021.01.13
Spring - 데이터 바인딩  (4) 2021.01.13
Spring - ResourceLoader  (64) 2021.01.12
Spring - ApplicationEventPublisher  (4) 2021.01.12
Spring - Messagesource  (2) 2021.01.12

댓글