Web Programing!/JAVA / JSP
[Springboot] Message properties 사용
어설픈봉봉이
2023. 8. 21. 10:26
반응형
SMALL
@Data
public class Dto {
@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 Dto {
@NotNull(message="{name.notnull}")
private String name;
....
}
DTO에서는 message="{validation.properties에서 정의한 key값}" 을 넣어주면 된다.
반응형