티스토리 뷰
들어오는 Data에 대한 검증은 어디에서나 필요하다.
@Data public class MemberDto { @NotNull(message="name must not be null") private String name; ... 후략 ... }
위와 같은 방식으로 DTO에 message를 하드코딩해서 각 항목별로 validation을 수행할 수 있지만 관리적인 측면이나 다국어 적용시 이는 문제가 될 수 있다. 이를 해결하기 위해 Spring에서 message를 사용하듯이 code(key) 값을 넣어서 별도의 공간에 정의되어 있는 message를 가지고 오고자 한다.
classpath:/messages/validation.properties
name.notnull=name must not be null
message.properties 파일에 넣어도 되지만 validation 관련된 내용은 validation.properties에 별도로 관리를 하고자 위와 같은 파일을 만들어서 이곳에 validation 관련된 내용을 넣어주었다.
WebConfig.java
import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.validation.Validator; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Bean public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:/messages/message"); messageSource.setDefaultEncoding("UTF-8"); return messageSource; } @Bean public MessageSource validationMessageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:/messages/validation"); messageSource.setDefaultEncoding("UTF-8"); return messageSource; } @Override public Validator getValidator() { LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean(); bean.setValidationMessageSource(validationMessageSource()); return bean; } }
MessageSource를 정의하는 곳에 추가적으로 validationMessageSource와 getValidator bean을 추가하였다. getValidator라는 녀석은 DTO에서 messageSource를 가지고 올 수 있게 해주는 역할을 해준다.
DTO.java
@Data public class MemberDto { @NotNull(message="{name.notnull}") private String name; ... 후략 ... }
마지막으로 DTO에서는 message="{validation.properties에서 정의한 key값}" 을 넣어주면 된다.
간단하게 validation message를 하드코딩에서 message로 전환을 완료하였다.
끝!
'Framework > Spring' 카테고리의 다른 글
Springboot에서 API Docs (Springdoc) 사용하는 방법 (1) (0) | 2021.02.18 |
---|---|
spring-boot-starter, parent 로 dependency 관리하기 (0) | 2021.02.10 |
Spring에서 h2 database 간단 사용법 (1) | 2021.02.03 |
Springboot 에서 @ComponentScan 설정 및 사용법 (2) | 2021.01.14 |
Springboot + Redis 연동하는 초간단 샘플 만들어보기 (3) | 2021.01.05 |
댓글