Java

[Spring Boot] Optional과 orElseThrow

연신내고독한늑대 2024. 7. 31. 20:00

# Optional과 orElseThrow란?

Optional은 Java 8에서 도입된 클래스 중 하나로, null을 안전하게 처리하기 위한 도구입니다. Optional 객체를 사용하면 값이 존재할 수도 있고, 존재하지 않을 수도 있는 상황을 명확하게 표현할 수 있습니다. orElseThrow는 Optional 객체에서 값을 가져올 때, 값이 없을 경우 지정한 예외를 발생시키는 메서드

 

# Optional과 orElseThrow를 사용하지 않았을 때

Optional과 orElseThrow를 사용하지 않으면, null 체크와 예외 처리가 별도로 필요

 

# 코드 비교

1. 사용하지 않았을 때 

// UserRepository.java
package com.example.demo.repository;
import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository <User, Integer> {
   User findByUserId (String userId);
}
// UserService.java
package com.example.demo.service;
import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import com.example.demo.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService {
  @Autowired
  private UserRepository userRepository;
  @Autowired
  private PasswordEncoder passwordEncoder;
  @Autowired
  private JwtUtil jwtUtil;

  public String login(String userId, String password) throws Exception {
    User user = userRepository.findByUserId(userId);
    if (user == null) {
       throw new Exception("User not found");
    }
    return "success"; 
}

 

2. 사용 했을 때 

// UserRepository.java
package com.example.demo.repository;
import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository <User, Integer> {
   Optional<User> findByUserId (String userId);
}
// UserService.java
package com.example.demo.service;
import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import com.example.demo.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService {
  @Autowired
  private UserRepository userRepository;
  @Autowired
  private PasswordEncoder passwordEncoder;
  @Autowired
  private JwtUtil jwtUtil;

  public String login(String userId, String password) throws Exception {
    User user = userRepository.findByUserId(userId)
                          .orElseThrow(() -> new Exception("User not found"));
    return "success"; 
}