728x90
반응형

Spring Boot

  • 스프링으로 작성된 단독 실행 가능한 어플리케이션을 개발하기 위한 플랫폼
  • 최소한의 설정으로 스프링의 플랫폼과 서드파티 라이브러리를 사용할 수 있게 됨
  • 웹 어플리케이션 서버(WAS)인 Tomcat 등 내장
    -> 실행 위해 별도의 서버 설치 X => 스프링 부트 실행 -> 웹 어플리케이션 실행
  • 스프링 부트 어플리케이션 -> 웹 어플리케이션 아카이브(WAR) 형태로 패키징 => 별도의 웹 어플리케이션 서버에 배포 가능
  • (기존) IoC, AOP 작업 -> 별도의 XML 파일에 설정 내용 추가 or 어노테이션 

      
@SpringBootApplication
public class MyRestfulServicesApplication {
public static void main(String[] args) {
Application application = SpringApplication.run(MyRestfulServicesApplication.class, args);
for (String str: application.getBeanDefinitionNames()) {
System.out.println(str);
}
}
}
  • Spring Boot Application: 메인 클래스 
  • Auto Configuration
    • 개발하고자 하는 어플리케이션에 필요한 설정 작업 자동으로 함, 필요에 따라 개발자가 등록한 환경 찾아 읽어옴
  • Component Scan
    • 프로젝트에 선언된 각종 컴포넌트들 읽어옴
    • 서비스, 레포지터리, 컨트롤러, entity, 일반 컴포넌트 등 여러가지 클래스 유형 존재
      클래스의 인스턴스 -> 스프링 컨테이너의 메모리로 읽어옴 
      => 어플리케이션에서 사용할 수 있는 형태인 빈 형태로 등록

=> 개발자가 프로그래밍에 의해 클래스의 인스턴스 직접 생성 X

스프링 컨테이너에 의해 인스턴스가 미리 생성, 생성된 인스턴스 호출해서 사용

=> 제어의 역전(IoC; Inversion of Control) : 컨테이너에 의해 클래스의 인스턴스가 관리


사용자 관리 API

User -> Post (1:N)

 

CRUD: Create(생성), Read(조회), Update(수정), Delete(삭제)

CRUD 기능이 있다 == 데이터베이스 or 스토리지에 어떤 작업을 추가하고 읽어들이고 변경하고 삭제하는 기능이 있다

  • (GET) /users, (POST) /users
  • (GET) /users/{id}, (DELETE) /users/{id}
  • (GET) /users/{id}/posts, (POST) /users/{id}/users

-> URI가 같지만, HTTP 메소드 다름 => 하나의 URI로도 2가지 기능할 수 있음


Spring Boot Project 생성

  • Project
    • gradle: Groovy 또는 Kotlin DSL 사용 -> 빌드 스크립트 작성
      • 빌드 스크립트 -> build.gradle 파일에 작성
      • 코드 형태로 작성 -> 유연하고 간결하게 빌드 구성
      • 유연성, 성능 향상
      • (+) 빌드 속도 ↑ => 큰 프로젝트에서 성능 ↑
    • maven: XML 사용하여 빌드 구성 정의
      • (+) 구조화된 형식으로 읽기 쉬움
      • (-) 빌드 속도 ↓ <- 모든 빌드 단계에서 프로젝트의 모든 정보를 다시 확인 
      • 프로젝트의 설정과 빌드 절차 -> pom.xml
  • Project Metadata
    • Group: 회사가 사용하고 있는 도메인
    • Artifact: 어플리케이션의 이름
    • Packaging
      • Jar: 독립형으로 인베디드 되어 있는 톰켓 실행
      • war: 패키징 되어 있는 war 파일을 별도의 웹 어플리케이션 서버에 배포해서 실행

Spring Boot Project 구조 확인과 실행 방법


      
package com.example.myrestfulservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class MyRestfulServiceApplication {
public static void main(String[] args) {
ApplicationContext ac = SpringApplication.run(MyRestfulServiceApplication.class, args);
// 스프링 context에 등록되어 진 초기 상태 빈들의 목록 반환
String[] allBeanNames = ac.getBeanDefinitionNames();
for (String beanNames : allBeanNames) {
System.out.println(beanNames);
}
}
}

HelloWorld Controller 추가


      
package com.example.myrestfulservice.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController // Spring context에 등록되게 하기 위해
public class HelloWorldController {
// GET
// URI - /hello-world
// @RequestMapping(method=RequestMethod.GET, path="/hello-world")
@GetMapping(path = "/hello-world") // 전달하고자 하는 http method 안적어도 됨
public String helloworld() {
return "Hello World";
}
}

HelloWorld Bean 추가

Lombok 라이브러리

  • 클래스에 대해 프로퍼티(property) 등록
    프로퍼티: 객체의 고유한 속성(특징), 필드(field, 멤버변수): 속성의 실체를 담는 곳
    -> Setter, Getter 메소드/ 초기화할 수 있는 생성자/ Equals, ToString 자바의 기본 오브젝트 클래스의 메소드 자동으로 생성
  • @Data: Data라는 어노테이션 사용 => 프로젝트에 필요한 클래스들 생성


      
package com.example.myrestfulservice.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor // 현재 가지고 있는 프로퍼티 다 사용하고 있는 생성자 추가
public class HelloWorldBean {
private String message;
// public HelloWorldBean(String message) {
// this.message = message;
// }
}

      
@GetMapping(path = "/hello-world-bean")
public HelloWorldBean helloWorldBean() {
// text 직접 전달 X object 타입, bean 타입으로 전달
return new HelloWorldBean("Hello World!");
}

DispatcherServelt과 프로젝트 동작의 이해

Spring Boot에서 필요한 설정 파일 

  • application.properties -> 설정이름: 값
  • application.yml -> 설정 이름 = 값 => 직관적

      
// properties
logging.level.org.springframework = debug
// yml
logging:
level:
org.springframework:debug

      
server:
port: 8088
logging:
level:
org.springframework: debug

 

Spring Boot Auto Configuration

  • DispatcherServletAutoConfiguration: 
    • Dispatcher Servlet: 사용자의 모든 요청 처리 받음
      => Dispatcher Servlet 관리
  • ErrorMvcAutoConfiguration: Error 처리
  • HttpMessageConverterAutoConfiguration -> JSON convert
    • 사용자의 요청에 따른 비즈니스 로직 처리, 결과 값을 API로 호출한 클라이언트로 다시 전달 
      => 전달하기 위한 데이터 포맷 처리

Dispatcher Servlet

  • (사전적 의미) Disaptch: 정보나 메시지를 다른 쪽으로 전달
  • 서블릿 컨테이너: 서블릿 어플리케이션을 실행할 수 있는 환경
  • 클라이언트의 모든 요청을 한 곳으로 받아서 처리
  • 요청에 맞는 Handler로 요청을 처리
  • Handler의 실행 결과 -> Http Response 형태로 만들어서 반환

RestController

 

  • Spring4부터 @RestController 지원
  • @Controller + @ResponseBody
  • view를 갖지 않는 REST Data(JSON/XML) 반환

Path Variable 이용 - 가변 URI 사용


      
@GetMapping(path = "/hello-world-bean/path-variable/{name}")
public HelloWorldBean helloWorldBeanPathVariable(@PathVariable String name) {
return new HelloWorldBean(String.format("Hello World, %s ", name));
}

출처

 

[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발 강의 | Dowon Lee - 인프런

Dowon Lee | 이 강의는 Spring Boot를 이용해서 RESTful Web Services 애플리케이션을 개발하는 과정에 대해 학습하는 강의으로써, REST API 설계에 필요한 기본 지식에 대해 학습할 수 있습니다., 스프링 부트

www.inflearn.com

 

 

 

728x90
반응형
김앩옹