@InitBinder๋ฅผ ์ฌ์ฉํ ๊ฒ์ฆ
@InitBinder
public void init(WebDataBinder dataBinder) {
log.info("init binder {}", dataBinder);
dataBinder.addValidators(itemValidator);
}
์ด๋ ๊ฒ 'WebDataBinder'์ ๊ฒ์ฆ๊ธฐ๋ฅผ ์ถ๊ฐํ๋ฉด ํด๋น ์ปจํธ๋กค๋ฌ์์๋ ๊ฒ์ฆ๊ธฐ๋ฅผ ์๋์ผ๋ก ์ ์ฉํ ์ ์๋ค.
'@InitBinder' -> ํด๋น ์ปจํธ๋กค๋ฌ์๋ง ์ํฅ์ ์ค๋ค. ๊ธ๋ก๋ฒ ์ค์ ์ ๋ณ๋๋ก ํด์ผํจ
์ด ํ ํด๋น ์ปจํธ๋กค๋ฌ์์ '@Validated' ์ด๋ ธํ ์ด์ ์ ๋ถ์ฌ์ฃผ๋ฉด ๋จ
'@Validated'๋ ๊ฒ์ฆ๊ธฐ๋ฅผ ์คํํ๋ผ๋ ์ด๋ ธํ ์ด์ ์ด๋ค.
์ด ์ด๋ ธํ ์ด์ ์ด ๋ถ์ผ๋ฉด ์์ 'WebDataBinder'์ ๋ฑ๋กํ ๊ฒ์ฆ๊ธฐ๋ฅผ ์ฐพ์์ ์คํํ๋ค. ๊ทธ๋ฐ๋ฐ ์ฌ๋ฌ ๊ฒ์ฆ๊ธฐ๋ฅผ ๋ฑ๋กํ๋ค๋ฉด ๊ทธ ์ค์ ์ด๋ค ๊ฒ์ฆ๊ธฐ๊ฐ ์คํ๋์ด์ผ ํ ์ง ๊ตฌ๋ถ์ด ํ์ํ๋ค.
์ด๋ 'supports()'๊ฐ ์ฌ์ฉ๋๋ค. ์ฌ๊ธฐ์๋ 'supperts(Item.class)'๊ฐ ํธ์ถ๋๊ณ , ๊ฒฐ๊ณผ๊ฐ 'true'์ด๋ฏ๋ก 'ItemValidator'์ 'validate()'๊ฐ ํธ์ถ๋๋ค.
* ์ถ๊ฐ๋ก ๊ฒ์ฆ์ ํ๊ธฐ ์ํด์ ํด๋น ์ปจํธ๋กค๋ฌ์ ItemValidator ์์ฑ์์ ItemValidator ํด๋์ค์ ๊ฒ์ฆ ๋ด์ฉ์ ์ ์ด๋๊ธด ํด์ผํ๋ค
private final ItemValidator itemValidator;
ItemValidator ํด๋์ค
//ItemValidator.java
package hello.itemservice.web.validation;
import hello.itemservice.domain.item.Item;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
@Component
public class ItemValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Item.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
Item item = (Item) target;
if (!StringUtils.hasText(item.getItemName())) {
errors.rejectValue("itemName", "required");
}
if(item.getPrice() == null || item.getPrice() < 1000 || item.getPrice() > 1000000){
errors.rejectValue("price", "range", new Object[]{1000, 1000000}, null);
}
if(item.getQuantity() == null || item.getQuantity() >= 9999) {
errors.rejectValue("quantity", "max", new Object[]{9999}, null);
}
//ํน์ ํ๋๊ฐ ์๋ ๋ณตํฉ ๋ฃฐ ๊ฒ์ฆ
if (item.getPrice() != null && item.getQuantity() != null) {
int resultPrice = item.getPrice() * item.getQuantity();
if (resultPrice < 10000) {
errors.reject("totalPriceMin", new Object[]{1000, resultPrice}, null);
}
}
}
}
๊ธ๋ก๋ฒ ์ค์ - ๋ชจ๋ ์ปจํธ๋กค๋ฌ์ ๋ค ์ ์ฉ
@SpringBootApplication
public class ItemServiceApplication implements WebMvcConfigurer {
public static void main(String[] args) {
SpringApplication.run(ItemServiceApplication.class, args);
}
@Override
public Validator getValidator() {
return new ItemValidator();
}
}
์ด๋ ๊ฒ ๊ธ๋ก๋ฒ ์ค์ ์ ์ถ๊ฐํ ์ ์๋ค. ๊ธฐ์กด ์ปจํธ๋กค๋ฌ์ '@InitBinder'๋ฅผ ์ ๊ฑฐํด๋ ๊ธ๋ก๋ฒ ์ค์ ์ผ๋ก ์ ์ ๋์ํ๋ ๊ฒ์ ํ์ธํ ์ ์๋ค.
ํ์ง๋ง ๊ธ๋ก๋ฒ ์ค์ ์ ํ๋ฉด BeanValidator๊ฐ ์๋ ๋ฑ๋ก๋์ง ์๋๋ฐ, ๊ธ๋ก๋ฒ ์ค์ ์ ์ง์ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ๋ ๋๋ฌผ๋ค.
'Languages | Frameworks > Spring' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[SpringBoot] RestApi ๊ตฌํํ๊ธฐ ์ํ List<Map> ์ฌ์ฉ (0) | 2022.05.02 |
---|---|
[SpringBoot] mybatis resultType HashMap Null๊ฐ ๋ฐ๊ธฐ (0) | 2022.05.02 |
์คํ๋ง์ด ์ง์ ๋ง๋ ์ค๋ฅ ๋ฉ์์ง ์ฒ๋ฆฌ - ํ์ ์๋ฌ์ฒ๋ฆฌ (0) | 2022.03.21 |
ValidationUtils (0) | 2022.03.21 |
MessageCodesResolver - ๋ฉ์ธ์ง ์ฐ์ ์์ ์ค์ (0) | 2022.03.21 |