프로그래밍/Java

[Spring, String Boot] StringUtils 사용 방법

차나니 2024. 4. 8. 14:44

StringUtils란 ?

StringUtils는 손쉽게 문자열을 다룰 수 있는 다양한 메서드를 제공하고 있습니다 !

StringUtils를 통해 유용한 메서드에 대해 몇 가지 정리해 보려합니다 :)

 

아래와 같이 Spring Framwork에서 기본적으로 제공해줍니다.

import org.springframework.util.StringUtils;

 

또는 apache의 모든 기능을 사용하려면 아래와 같이 defendency를 주입해줘야합니다 ! ( gradle 기준 코드)

implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0'

 

유용한 메서드

isEmpty()

문자열의 null 여부와, 길이가 0이 아닌지 체크해줍니다.

// 사용예제)
boolean bool = StringUtils.isEmpty(String);

// 코드 상세 내용)
public static boolean isEmpty(@Nullable Object str) {
	return (str == null || "".equals(str));
}

 

hashText()

문자열이 null 인 것과 길이가 0인 것 공백("", " ")인 것이 포함되어있다면 false를 반환해줍니다.

파라미터 값으로 null을 전달했을 때 NullPointException을 발생시키지 않습니다 !

// 사용예제)
boolean bool = StringUtils.hasText(String);

// 코드 상세 내용)
public static boolean hasText(@Nullable String str) {
    return (str != null && !str.isEmpty() && containsText(str));
}