@Valid vs @Validated

Reference:Baeldung - Differences in @Valid and @Validated Annotations in Spring

@Valid and @Validated

@Valid๋ฅผ ์ ์šฉํ•  ๋•Œ๋Š” ์ œ์•ฝ์กฐ๊ฑด์„ ์„ค์ •ํ•œ ์†์„ฑ์— ๋Œ€ํ•ด ์ „๋ถ€ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ํ•˜๊ฒŒ ๋˜๋Š”๋ฐ, ๋งŒ์•ฝ ์ œ์•ฝ์กฐ๊ฑด์€ ๊ทธ๋Œ€๋กœ ์„ ์–ธํ•˜๋˜ **์›ํ•˜๋Š” ์†์„ฑ๋งŒ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ํ•˜๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ**์— @Validated ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค

@Valid vs @Validated

Target

@Validated ๋Š” @Valid ์˜ ๊ธฐ๋Šฅ์„ ํฌํ•จํ•œ๋‹ค

โ†’ @Valid ๋ฅผ ์ ์šฉํ•œ ๊ณณ์ด๋ผ๋ฉด @Validated ๋กœ ๋ณ€๊ฒฝ ๊ฐ€๋Šฅํ•˜๋‹ค

  • @Valid

    • parameter๋‚˜ method ๋‚ด ๊ฐ์ฒด์˜ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ์ˆ˜ํ–‰ํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋œ๋‹ค

    • class ์ˆ˜์ค€ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ์—๋Š” ์‚ฌ์šฉ๋˜์ง€ ์•Š๋Š”๋‹ค

  • @Validated

    • method ์ˆ˜์ค€์˜ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ์™€ class ์ˆ˜์ค€ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ๋ชจ๋‘ ์ง€์›ํ•œ๋‹ค

Group Validation Support

  • @Valid

    • Group ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ์ง€์›ํ•˜์ง€ ์•Š๋Š”๋‹ค

  • @Validated

    • ๊ฒ€ํ† ํ•  ๊ฒ€ํ†  option์˜ group์„ ์ง€์ •ํ•  ์ˆ˜ ์žˆ๋‹ค

    • group์„ ์ง€์ •ํ•˜์—ฌ ํŠน์ • group์— ๋Œ€ํ•œ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ์ ์šฉํ•˜๊ฑฐ๋‚˜ ์ƒ๋žตํ•  ๋•Œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค

Validation Method

  • @Valid

    • javax.validation.Validator

  • @Validated

    • org.springframework.validation.Validator

      • Spring์˜ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ ๋ฐฉ๋ฒ•๊ณผ ํ†ตํ•ฉ๋˜์–ด ์žˆ๋‹ค

      • @Validated annotation์„ ์‚ฌ์šฉํ•˜๋ฉด Spring์€ Validator ๊ตฌํ˜„์ฒด๋ฅผ ํ™œ์šฉํ•˜์—ฌ ํ•ด๋‹น ๊ฐ์ฒด์˜ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ์ˆ˜ํ–‰ํ•œ๋‹ค

Exception Handling

  • @Valid

    • javax.validation.ConstraintViolationException ์ด ๋ฐœ์ƒํ•œ๋‹ค

  • @Validated

    • Spring์˜ MethodArgumentNotValidException or BindException์ด ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ์ด๋Ÿฌํ•œ ์˜ˆ์™ธ๋ฅผ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•œ custom message๋‚˜ handler๋ฅผ ๊ตฌ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค

Last updated