ysk(0soo)
Lifealong
ysk(0soo)
전체 방문자
오늘
어제
  • 분류 전체보기 (238)
    • Java (50)
      • whiteship-java-study (11)
      • Java (28)
      • time (6)
    • Spring (68)
      • JPA (15)
      • Spring (1)
      • SpringBoot (1)
      • SpringMVC (6)
      • Spring Security (22)
      • Jdbc (1)
      • RestDocs (14)
      • log (6)
    • Kotlin (3)
    • Web (2)
      • nginx (1)
    • Database (14)
      • MySQL (5)
      • PostgreSQL (1)
      • SQL (1)
      • Redis (4)
    • C, C++ (0)
    • Git (1)
    • Docker (2)
    • Cloud (3)
      • AWS (3)
    • 도서, 강의 (0)
      • t5 (0)
    • 기타 (7)
      • 프로그래밍 (1)
    • 끄적끄적 (0)
    • CS (14)
      • 운영체제(OS) (2)
      • 자료구조(Data Structure) (9)
    • 하루한개 (12)
      • 우아한 테크코스-10분테코톡 (12)
    • 스터디 (12)
      • 클린 아키텍처- 로버트마틴 (2)
      • JPA 프로그래밍 스터디 (10)
    • 테스트 (34)
      • JUnit (19)
      • nGrinder (2)
      • JMeter (0)
    • Infra (3)
    • 프로그래머스 백엔드 데브코스 3기 (0)
    • 디자인 패턴 (3)
    • Issue (4)
    • system (1)
      • grafana (0)
      • Prometheus (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • github

공지사항

인기 글

태그

  • nGrinder
  • DataJpaTest
  • 구조화된 동시성
  • 가상 스레드
  • FilterSecurityInterceptor
  • StructuredConcorrency
  • AccessDecisionVoter 커스텀
  • junit5
  • 정규표현식
  • node exporter basic auth
  • UserDetailsService
  • 트랜잭션
  • 인가(Authorization) 처리
  • restdocs enum
  • java
  • 동등성
  • 동시성 제어
  • jpa
  • scope value
  • AccessDecisionManager
  • querydsl
  • AuthenticationException
  • tree
  • LocalDateTime
  • 동일성
  • restdocs custom
  • 가상 스레드 예외 핸들링
  • mysql
  • VirtualThread Springboot
  • nginx basic auth

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ysk(0soo)

Lifealong

Kotlin

Kotlin List Validation - 리스트 타입 파라미터 검증

2023. 1. 3. 04:14

코틀린 + Spring Boot 환경에서 Request 를 검증할 때,

String 타입의 List를 Null과 빈 값을 허용하지 않기 위한 @NotBlank 어노테이션으로는, List 타입의 필드를 검증할 수 없다.

 

자바에서는 다음처럼 사용할 수 있지만 코틀린에서는 사용할 수 없다.

public class Request {
  private List<@NotBlank String> inputs;
}

@field:NotBlack 와 @get:NotBlank 둘 다 사용할 수 없다.

  • 필드나 getter에 걸고 싶기때문에 field:를 명시해줘야 하지만, 이 방법이 통하지 않는다.

해결하기 위해서 사용자 지정 validation annotation을 만들어야 한다.

@NotBlank List Elements Custom Validation Annotation

먼저 어노테이션을 선언한다

@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Constraint(validatedBy = [NotBlankElementListValidator::class])
annotation class NotBlankElementList(
    val message: String = "리스트 안에 빈 값이 존재합니다.",
    val groups: Array<KClass<*>> = [],
    val payload: Array<KClass<*>> = [],
)

Validator를 구현한다.

class NotBlankElementListValidator : ConstraintValidator<NotBlankElementList, List<String>> {

    override fun isValid(lists: List<String>?, context: ConstraintValidatorContext?): Boolean {
        if (lists == null) {
            return false
        }
        return lists.none { StringUtils.isEmpty(it) }
    }
}
  • 단순히 List 파라미터 자체가 null값인지, 또는 StringUtils를 이용하여 empty String인지 검사하는 로직이다

Request DTO에 적용한다

class Request(

    @field:NotNull
    val requestId: Long,

    @field:NotBlank
    val name: String,

    @NotBlankElementList
    val texts: List<String>

) 
  • https://stackoverflow.com/questions/51085138/kotlin-data-class-and-bean-validation-with-container-element-constraints
  • https://kotlinlang.org/docs/whatsnew14.html#type-annotations-in-the-jvm-bytecode
  • https://stackoverflow.com/questions/70215736/kotlin-spring-boot-bean-validation-not-working
저작자표시 비영리 (새창열림)

'Kotlin' 카테고리의 다른 글

[코틀린]코루틴(coroutine)  (0) 2023.05.09
Kotlin Querydsl 설정  (0) 2023.01.26
    'Kotlin' 카테고리의 다른 글
    • [코틀린]코루틴(coroutine)
    • Kotlin Querydsl 설정
    ysk(0soo)
    ysk(0soo)
    백엔드 개발을 좋아합니다. java kotlin spring, infra 에 관심이 많습니다. email : kim206gh@naver.com github : https://github.com/devysk

    티스토리툴바