티스토리 뷰

들어오는 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를 정의하는 곳에 추가적으로 validationMessageSourcegetValidator 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로 전환을 완료하였다. 

 

끝!

댓글
최근에 올라온 글
최근에 달린 댓글
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30