1. Dependency 추가
<dependency>
<groupId>dev.akkinoc.util</groupId>
<artifactId>yaml-resource-bundle</artifactId>
<version>2.8.0</version>
</dependency>
2. YamlMessageSource 생성
public class YamlMessageSource extends ResourceBundleMessageSource {
@Override
protected ResourceBundle doGetBundle(String basename, Locale locale) throws MissingResourceException {
return ResourceBundle.getBundle(basename, locale, YamlResourceBundle.Control.INSTANCE);
}
}
3. Yaml Message Resource 등록
@Configuration
@ConfigurationProperties(prefix = "spring.messages")
public class YamlMessageConfig {
private String basename;
private String encoding;
private int cacheDuration;
private boolean alwaysUseMessageFormat;
private boolean useCodeAsDefaultMessage;
private boolean fallbackToSystemLocale;
@Bean
public MessageSource messageSource() {
YamlMessageSource messageSource = new YamlMessageSource();
messageSource.setBasename(this.basename);
messageSource.setDefaultEncoding(this.encoding);
messageSource.setCacheSeconds(this.cacheDuration);
messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat);
messageSource.setUseCodeAsDefaultMessage(this.useCodeAsDefaultMessage);
messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
return messageSource;
}
}
4. application.yml 설정 추가
spring:
messages:
basename: messages
encoding: UTF-8
5. Validation DTO 추가
@Getter
@Setter
public class ValidDto {
@NotNull
private String name1;
@NotEmpty
private String name2;
@NotBlank
private String name3;
private String name4;
private String name5;
@AssertTrue
private boolean insertable;
@Email
private String email1;
}
6. Controller의 메소드에 DTO 추가 + @Valid
@RestController
@RequestMapping("/valid")
public class ValidRestController {
@PostMapping("validation1")
public ValidDto validation1(@RequestBody @Validated ValidDto param){
return param;
}
}
7. ControllerAdvice 추가
@RestControllerAdvice
public class ValidControllerAdvice {
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String,String > handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors()
.forEach(c -> errors.put(((FieldError) c).getField(), c.getDefaultMessage()));
return errors;
}
}
8. Postman 테스트