Spring Boot 기초
DI, IoC, REST API 기초
학습 항목
본 콘텐츠의 이미지 및 내용은 AI로 생성되었습니다.
이미지 로딩 중...
Spring Boot 기초부터 심화까지 완벽 가이드
Spring Boot의 기본 개념부터 고급 기능까지 단계별로 학습합니다. 초급 개발자가 실무에서 바로 사용할 수 있는 핵심 개념과 코드 예제를 제공합니다.
들어가며
이 글에서는 Spring Boot 기초부터 심화까지 완벽 가이드에 대해 상세히 알아보겠습니다. 총 12가지 주요 개념을 다루며, 각각의 개념에 대한 설명과 실제 코드 예제를 함께 제공합니다.
목차
- Spring Boot 애플리케이션 시작하기
- REST Controller 만들기
- Dependency Injection 의존성 주입
- application properties 설정
- Entity와 JPA Repository
- POST 요청 처리하기
- Service Layer 패턴
- Exception Handling 예외 처리
- Path Variable과 Query Parameter
- Custom Query with JPA
- DTO Pattern 데이터 전송 객체
- Validation 데이터 검증
1. Spring Boot 애플리케이션 시작하기
개요
@SpringBootApplication 어노테이션으로 Spring Boot 애플리케이션을 간단하게 시작할 수 있습니다.
코드 예제
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
설명
@SpringBootApplication은 자동 설정, 컴포넌트 스캔, 설정 클래스 기능을 한 번에 활성화합니다.
2. REST Controller 만들기
개요
@RestController와 @GetMapping을 사용하여 간단한 REST API를 만들 수 있습니다.
코드 예제
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot!";
}
}
설명
@RestController는 JSON 응답을 자동으로 반환하며, @GetMapping은 HTTP GET 요청을 처리합니다.
3. Dependency Injection 의존성 주입
개요
@Autowired를 사용하여 다른 컴포넌트를 자동으로 주입받을 수 있습니다.
코드 예제
@Service
public class UserService {
private final UserRepository repository;
@Autowired
public UserService(UserRepository repository) {
this.repository = repository;
}
}
설명
생성자 주입 방식으로 의존성을 주입하면 테스트하기 쉽고 불변성을 보장할 수 있습니다.
4. application properties 설정
개요
application.properties 파일에서 애플리케이션 설정을 관리할 수 있습니다.
코드 예제
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
설명
포트, 데이터베이스 연결 정보, JPA 설정 등을 외부 파일로 관리하여 유연성을 높입니다.
5. Entity와 JPA Repository
개요
@Entity로 데이터베이스 테이블을 정의하고 JpaRepository로 CRUD 작업을 자동화합니다.
코드 예제
@Entity
public class User {
@Id @GeneratedValue
private Long id;
private String name;
}
public interface UserRepository extends JpaRepository<User, Long> {
}
설명
JpaRepository를 상속받으면 기본 CRUD 메서드를 자동으로 사용할 수 있습니다.
6. POST 요청 처리하기
개요
@PostMapping과 @RequestBody로 클라이언트의 JSON 데이터를 받아 처리합니다.
코드 예제
@PostMapping("/users")
public User createUser(@RequestBody User user) {
return userRepository.save(user);
}
설명
@RequestBody는 HTTP 요청 본문의 JSON을 자동으로 User 객체로 변환합니다.
7. Service Layer 패턴
개요
비즈니스 로직을 Service 계층으로 분리하여 코드를 구조화합니다.
코드 예제
@Service
public class UserService {
@Autowired
private UserRepository repository;
public List<User> getAllUsers() {
return repository.findAll();
}
}
설명
Controller는 HTTP 처리만, Service는 비즈니스 로직만 담당하여 관심사를 분리합니다.
8. Exception Handling 예외 처리
개요
@ExceptionHandler로 전역 예외를 처리하여 일관된 에러 응답을 제공합니다.
코드 예제
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
return ResponseEntity.status(500).body(e.getMessage());
}
}
설명
@RestControllerAdvice는 모든 컨트롤러의 예외를 한 곳에서 처리합니다.
9. Path Variable과 Query Parameter
개요
URL 경로와 쿼리 파라미터를 통해 동적으로 데이터를 받을 수 있습니다.
코드 예제
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
@GetMapping("/search")
public List<User> search(@RequestParam String name) {
return userService.findByName(name);
}
설명
@PathVariable은 URL 경로에서, @RequestParam은 쿼리 문자열에서 값을 추출합니다.
10. Custom Query with JPA
개요
@Query 어노테이션으로 커스텀 쿼리를 작성할 수 있습니다.
코드 예제
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u WHERE u.name LIKE %:name%")
List<User> searchByName(@Param("name") String name);
}
설명
JPQL을 사용하여 복잡한 조회 로직을 Repository 메서드로 정의합니다.
11. DTO Pattern 데이터 전송 객체
개요
Entity와 클라이언트 간 데이터 전송을 위해 DTO를 사용합니다.
코드 예제
public class UserDTO {
private String name;
private String email;
public static UserDTO from(User user) {
return new UserDTO(user.getName(), user.getEmail());
}
}
설명
DTO를 사용하면 필요한 데이터만 전송하고 Entity의 내부 구조를 숨길 수 있습니다.
12. Validation 데이터 검증
개요
@Valid와 validation 어노테이션으로 입력 데이터를 자동 검증합니다.
코드 예제
public class UserDTO {
@NotBlank(message = "이름은 필수입니다")
private String name;
@Email(message = "유효한 이메일을 입력하세요")
private String email;
}
@PostMapping("/users")
public User create(@Valid @RequestBody UserDTO dto) {
return userService.create(dto);
}
설명
@Valid는 요청 데이터를 자동으로 검증하고, 실패 시 400 에러를 반환합니다.
마치며
이번 글에서는 Spring Boot 기초부터 심화까지 완벽 가이드에 대해 알아보았습니다. 총 12가지 개념을 다루었으며, 각각의 사용법과 예제를 살펴보았습니다.
관련 태그
#Spring Boot #REST API #Dependency Injection #JPA #Configuration