[SpringBoot] 스프링부트 맛보기_Optional

미나·2023년 10월 16일

새로알게된 정보

목록 보기
15/23

java 언어 설계자인 Brian Goetz는 Optional을 만든 의도를 다음과 같이 공식 API 문서에 작성해 두었다.

API Note:
	Optional is primarily intended for use as a method return type 
    where there is a clear need to represent "no result," and 
    where using null is likely to cause errors. 
    A variable whose type is Optional should never itself be null;
    it should always point to an Optional instance.
    
    메소드가 반환할 결과 값이 '없음'을 명백하게 표현할 필요가 있고, 
    null 을 반환하면 에러가 발생할 가능성이 높은 상황에서 메소드의 반환 타입으로 
    Optional 을 사용하자는 것이 Optional 을 만든 주된 목적이다.
	Optional 타입의 변수의 값은 절대 null 이어서는 안 되며, 
    항상 Optional 인스턴스를 가리켜야 한다.
| 출처 : coco3o |
  • Optional 사용 예시
import static org.junit.jupiter.api.Assertions.assertTrue;

@SpringBootTest
class Basic1ApplicationTests {

  @Autowired
  private QuestionRepository questionRepository;

  @Test
  void contextLoads() {
    Optional<Question> oq = this.questionRepository.findById(1);
    assertTrue(oq.isPresent());
    Question q = oq.get();
    q.setSubject("수정된 제목");
    this.questionRepository.save(q); 
  } 
}
: findById(1)로 데이터를 가져올때 데이터가 null값일수도 있기때문에 Optional로 확인한다.
+ assertTrue
: AssertTrue는 true를 return했을 땐 validation 성공, false를 return 했을 땐 validation 실패를 알리는 annotation이다. assertTrue를 사용하는 Method의 Name은 is로 시작해야한다.
| 출처 : dnwlsrla40.log |

1) Optional 객체 생성

Optional<Question> oq = this.questionRepository.findById(1);

2) Optional 객체 접근

if(oq.isPresent()){
    return oq.get();
}else{
    return oq.orElse(null);
}
String isNull;
String name;
        
isNull = "loose";
name = Optional.ofNullable(isNull).orElse("test");

System.out.println(name); //isNull값이 null이 아니므로 "loose" 출력

isNull = null;
name = Optional.ofNullable(isNull).orElse("test");

System.out.println(name); //isNull값이 null이므로 "test" 출력
| 출처 : loose |
2-1) get( ) : Optional 내부에 담긴 객체를 반환한다. 만약 null인 객체라면 NoSuchElementException이 발생한다. 따라서 isPresent( )로 체크한후 Get메서드 를 사용한다.
2-2) orElse(A) : Optional에 올 값이 null인 경우 orElse 안에 있는 내용(A)을 실행 시킨다.

0개의 댓글