SEB/TIL
042 | DTO ์ ํจ์ฑ ๊ฒ์ฆ
kexon
2022. 8. 23. 01:23
๐DTO ์ ํจ์ฑ ๊ฒ์ฆ์ด ํ์ํ ์ด์
- ์๋ฐ์คํฌ๋ฆฝํธ๋ก ์ ์ก๋๋ ๋ฐ์ดํฐ๋ ๋ธ๋ผ์ฐ์ ์ ๊ฐ๋ฐ์ ๋๊ตฌ์์ ๊ฐ์ ์กฐ์ํ ์ ์๊ธฐ ๋๋ฌธ์ ํ๋ก ํธ์๋ ์ชฝ์์ ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ์งํํ๋ค๊ณ ํ๋๋ผ๋ ์๋ฒ ์ชฝ์์ ํ๋ฒ ๋ ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ์งํํด์ผ ํ๋ค.
- ํ๋ก ํธ์๋ ์ชฝ์์ ์งํํ๋ ์ ํจ์ฑ ๊ฒ์ฆ ํ๋ก์ธ์ค๋ ์ฌ์ฉ์ ํธ์์ฑ ์ธก๋ฉด์์ ํ์ํ ์์ ์ด๋ค.
๐DTO ํด๋์ค์ ์ ํจ์ฑ ๊ฒ์ฆ ์ ์ฉํ๊ธฐ
๐งฉ ์ ํจ์ฑ ๊ฒ์ฆ์ ์ํ ์์กด ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ถ๊ฐ
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-validation:2.7.3'
}
๐@PathVariable ์ ํจ์ฑ ๊ฒ์ฆ
- @PathVariable์์ ์ ํจ์ฑ ๊ฒ์ฆ์ ํ๋ ค๋ฉด ํด๋์ค์ @Validated์ ๋ถ์ฌ์ค์ผ ํ๋ค. ์ ๋ถ์ด๋ฉด @Min(1)์ด ์์ฉ์ด ์๋ค
๐Jakarta Bean Validation
- ์ ๋ํ ์ด์ ๊ธฐ๋ฐ ์ ํจ์ฑ ๊ฒ์ฆ์ ์ํ ํ์ค ์คํ์ด๋ค.
- Jakarta Bean Validation์ ์ ๋ํ ์ด์ ์ ์ด์ฉํ๋ฉด Controller ๋ก์ง์์ ์ ํจ์ฑ ๊ฒ์ฆ ๋ก์ง์ ๋ถ๋ฆฌํ ์ ์๋ค.
- Jakarta Bean Validation์์ ๋นํธ์ธ(Built-in)์ผ๋ก ์ง์ํ์ง ์๋ ์ ๋ํ ์ด์ ์ Custom Validator๋ฅผ ํตํด Custom Annotation์ ๊ตฌํํ ํ, ์ ์ฉํ ์ ์๋ค.
๐Custom Validator๋ฅผ ์ฌ์ฉํ ์ ํจ์ฑ ๊ฒ์ฆ
- DTO ํด๋์ค์ ์ ํจ์ฑ ๊ฒ์ฆ ์ ์ฉ ์ Jakarta Bean Validation์ ๋ด์ฅ๋(Built-in) ์ ๋ํ ์ด์ ์ค ์ํ๋ ์ ๋ํ ์ด์ ์ด ์กด์ฌํ์ง ์์ ์ ์๋๋ฐ, ์ด ๋ ์ํ๋ ๋ชฉ์ ์ ๋ง๋ ์ ๋ํ ์ด์ ์ ์ง์ ๋ง๋ค์ด์ ์ ํจ์ฑ ๊ฒ์ฆ์ ์ ์ฉํ ์ ์๋ค.
- Custom Validator ๊ตฌํ ์ํ ์ ์ฐจ
- Custom Validator๋ฅผ ์ฌ์ฉํ๊ธฐ ์ํ Custom Annotation ์ ์
- ์ ์ํ Custom Annotation์ ๋ฐ์ธ๋ฉ ๋๋ Custom Validator ๊ตฌํ
CustomValidator๋ฅผ ๊ตฌํํ๊ธฐ ์ํด์๋ ConstraintValidator ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํด์ผ ํจ - ์ ํจ์ฑ ๊ฒ์ฆ์ด ํ์ํ DTO ํด๋์ค์ ๋ฉค๋ฒ ๋ณ์์ Custom Annotation ์ถ๊ฐ