본문 바로가기
개발/스프링(Spring)

Spring ) Assert 사용하기 (if 대용)

by kakk789 2023. 2. 2.
if문 대신 인수를 검증하고 조건에 맞지 않는 경우,
IllegalArgumentException 또는 IllegalStateException 예외를 발생 시킴

문자열 파악하는 예시 (true, false 반환)

  • null을 포함해서 공백만 존재한다면 False를 반환

Assert 적용 전 if문

if(!StringUtils.hasText(user)) {
    throw new IllegalArgumentException("User가 없습니다.");
}

Assert 적용

import org.springframework.util.Assert;

/*------------------------------------------------------------------*/

Assert.hasText(user, "User가 없습니다.");

Assert.class 내 hasText 동작원리

  • 클래스 정의로 이동해보면 아래와 같이 정의되어 있음
public static void hasText(@Nullable String text, Supplier<String> messageSupplier) {
    if (!StringUtils.hasText(text)) {
        throw new IllegalArgumentException(nullSafeGet(messageSupplier));
    }
}
반응형

댓글