Kotlin Annotations (Use-Site Targets)

About

Java๋กœ Spring Framework๋ฅผ ์‚ฌ์šฉํ•ด๋ดค๋‹ค๋ฉด ์•Œ๊ฒ ์ง€๋งŒ ์–ด๋…ธํ…Œ์ด์…˜(@XXXX)์ด ์ •๋ง ๋งŽ๋‹ค. @Bean, @Component, @Service, @Repository, @Configuration ๋ฟ ์•„๋‹ˆ๋ผ JPA์™€ Validation ๋“ฑ๊นŒ์ง€ ์ถ”๊ฐ€ํ•˜๋ฉด @Entity, @Email, @NotEmpty ๋“ฑ ๋‹ค์–‘ํ•˜๋‹ค. ์‚ฌ์šฉ ๋ฐฉ์‹์€ ๋ณดํ†ต ํด๋ž˜์Šค, ํ•„๋“œ ๋“ฑ์˜ ์œ„์— ์ ์–ด์ฃผ๋ฉด ๋œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด ๋‹ค์Œ๊ณผ ๊ฐ™์€ DTO๊ฐ€ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜์ž.

@Getter
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class UserRegisterRequest {

    @Email(message = "{user.register.email.invalid_format}")
    private String email;
    
    @Min(value = 18, message = "{user.register.age.too_young}")
    @Max(value = 25, message = "{user.register.age.too_old}")
    private int age;
    
    @Size(min = 16, max = 32, message = "{user.register.password.size.too_short}")
    private String password;
}

์ฝ”ํ‹€๋ฆฐ๊ณผ Spring์„ ์‚ฌ์šฉํ•  ๋•Œ, ํŠนํžˆ validation ์ ์šฉํ•  ๋•Œ ์ฃผ์˜ํ•  ์ ์€ ํ•„๋“œ ์œ„์—๋Š” ๋ฐ”๋กœ ์–ด๋…ธํ…Œ์ด์…˜์„ ๋ถ™์ด๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ํƒ€๊ฒŸ์„ ์ •ํ•ด์ค˜์•ผ ํ•œ๋‹ค.

data class UserRegisterRequest(
    @field:Email(message = "{user.register.email.invalid_format}")
    val email: String
    
    @field:[
        @Min(value = 18, message = "{user.register.age.too_young}")
        @Max(value = 25, message = "{user.register.age.too_old}")
    ]
    val age: Int
    
    @field:Size(min = 16, max = 32, message = "{user.register.password.size.too_short}")
    val password: String
)
  • ์ ์šฉํ•˜๋ ค๋Š” ๋ฒ”์œ„์— ๋”ฐ๋ผ @field, @set, @param, @property ๋“ฑ์ด ์žˆ๋‹ค.

  • ์ ์šฉํ•˜๋ ค๋Š” ์–ด๋…ธํ…Œ์ด์…˜์ด ์—ฌ๋Ÿฌ ๊ฐœ (e.g., @A, @B)๋ผ๋ฉด @field[A B]์™€ ๊ฐ™์ด ๊ตฌ๋ถ„์ž(,) ์—†์ด []๋กœ ๊ฐ์‹ธ์ฃผ๋ฉด ๋œ๋‹ค.

REF

Last updated