springboot

[spring boot] 1. 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 요약

jeri 2024. 7. 6. 13:47
반응형

✅ 개요

강의를 수강한 이유

  • 갓 영한님의 "스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술" 강의를 수강하였다.
  • 지난 국비 학원에서 스프링으로 웹개발을 하면서 스프링 프레임워크를 사용했고, 스프링 제공해주는 핵심기술과 MVC에 대한 전반적인 이해를 완료했다고 생각하여, 현업에서 가장 많이 사용하고 있는 스프링부트에 대한 기술도 습득하고자 이 강의를 수강하였다.
  • 무료강의였지만, 스프링부트에 대한 전반적인 흐름 얇고 넓게 학습할 수 있었던 알찬 강의다.

강의 링크

 

[지금 무료] 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 강의 | 김영한 - 인프

김영한 | 스프링 입문자가 예제를 만들어가면서 스프링 웹 애플리케이션 개발 전반을 빠르게 학습할 수 있습니다., 스프링 학습 첫 길잡이! 개발 공부의 길을 잃지 않도록 도와드립니다. 📣 확

www.inflearn.com

 

🔗 사이트 링크 모음zip

 

스프링 부트

DB

static 폴더

타임리프 템플릿엔진

자주하는 질문

https://docs.google.com/document/d/1j0jcJ9EoXMGzwAA2H0b9TOvRtpwlxI5Dtn3sRtuXQas/edit#heading=h.1d76fb6akfa7

 

자주 하는 질문

인프런 스프링, JPA 강의 자주 하는 질문 목차 목차 질문하기 질문하는 방법 질문용 파일 업로드 - 구글 드라이브 업로드 공통 강의 코스 문의 학습 방법 문의 블로그 정리, 깃허브 업로드 실행중

docs.google.com

 

✅ 강의 요약

0) 프로젝트 선택

 

build.gradle
plugins {
	id 'java'
	id 'org.springframework.boot' version '3.3.1'
	id 'io.spring.dependency-management' version '1.1.5'
}

group = 'hello'
version = '0.0.1-SNAPSHOT'

java {
	toolchain {
		languageVersion = JavaLanguageVersion.of(17)
	}
}

repositories {
	mavenCentral()
}


//Gradle은 의존관계가 있는 라이브러리를 함께 다운로드 함
//1. 스프링 부트 라이브러리
// => spring-boot-starter-web : spring-boot-starter-tomcat: 톰캣 (웹서버), spring-webmvc: 스프링 웹 MVC
// => spring-boot-starter-thymeleaf: 타임리프 템플릿 엔진(View)
// => spring-boot-starter(공통): 스프링 부트 + 스프링 코어 + 로깅
//2. 테스트 라이브러리
// => spring-boot-starter-test : junit: 테스트 프레임워크,  mockito: 목 라이브러리, assertj: 테스트 코드를 좀 더 편하게 작성하게 도와주는 라이브러리, spring-test: 스프링 통합 테스트 지원

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

tasks.named('test') {
	useJUnitPlatform()
}

 

1) 프로젝트를 빌드하고 실행하는 법

  • 콘솔로 이동
  • 폴더 목록 확인 ls
  • ./gradlew build
  • cd build/libs
  • java -jar hello-spring-0.0.1-SNAPSHOT.jar
  • 콘솔에서 실행확인

2) 정적컨텐츠

3) MVC와 템플릿 엔진

@Controller
  public class HelloController {

    // [실행]: <http://localhost:8080/hello-mvc?name=spring>
    // => MVC와 템플릿 엔진 - [Controller - HelloController의 hello(Model model) 요청처리메소드], [View - hello-template.html] , [Model]
    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model) { //@RequestParam 어노테이션은 required가 기본적으로 true 이므로, 값을 반드시 넘겨야함
        model.addAttribute("name", name);
        return "hello-template";
    }
}
    • 컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버가 화면을 찾아서 처리함
    • 스프링 부트 템플릿엔진 기본 viewName 매핑은 resources:templates/ +{ViewName}+ .html

4) API

@Controller
  public class HelloController {

    // [실행]: <http://localhost:8080/hello-api?name=spring>
    // => API - @ResponseBody 객체 반환 - viewResolver 대신에 MappingJackson2HttpMessageConverter가 동작
    // => @ResponseBody를 사용하고 객체를 반환(Hello객체)하면 객체가 JSON으로 변환됨
    @GetMapping("hello-api")
    @ResponseBody
    public Hello helloApi(@RequestParam("name")String name){
        Hello hello = new Hello();
        hello.setName(name);
        return hello;
    }
    }
}
  • 클라이언트의 HTTP Accept 해더와 서버의 컨트롤러 반환 타입 정보 둘을 조합해서 HttpMessageConverter 가 선택됨
  • @ResponseBody 문자 반환
    • viewResolver 대신에 StringHttpMessageConverter가 동작
    • @ResponseBody를 사용하면 뷰 리졸버를 사용하지 않음
    • 대신에 HTTP의 BODY에 문자 내용을 직접 반환
    • 즉, HTTP 헤더 응답 바디부에 직접 ["hello" + name]을 넣으므로 요청한 클라이언트에게 문자가 그대로 넘어감
    • 기본 문자처리: StringHttpMessageConverter
  • @ResponseBody 객체 반환
    • viewResolver 대신에 MappingJackson2HttpMessageConverter가 동작
    • @ResponseBody를 사용하고 객체를 반환(Hello객체)하면 객체가 JSON으로 변환됨
    • 기본 객체처리: MappingJackson2HttpMessageConverter

5) 일반적인 웹 애플리케이션 계층 구조

  • 컨트롤러: 웹 MVC의 컨트롤러 역할
  • 서비스: 핵심 비즈니스 로직 구현
  • 리포지토리: 데이터베이스에 접근, 도메인 객체를 DB에 저장하고 관리
  • 도메인: 비즈니스 도메인 객체 예) 회원, 주문, 쿠폰 등등 주로 데이터베이스에 저장하고 관리됨

 

    • 아직 데이터 저장소가 선정되지 않을 때 클래스 간 의존관계 및 스프링 설정 관계 (인터페이스로 구현 클래스를 변경할 수 있도록 설계 - 확장가능하도록)

6) 스프링 빈과 의존관계

  • 스프링 빈 등록
    • @Component 애노테이션이 있으면 스프링 빈으로 자동 등록됨
    • @Component를 포함하는 애노테이션 : @Controller , @Service , @Repository
    • 스프링은 스프링 컨테이너에 스프링 빈을 등록할 때, 기본으로 싱글톤으로 등록함
    • 따라서 같은 스프링 빈이면 모두 같은 인스턴스임
    • 설정으로 싱글톤이 아니게 설정할 수 있지만, 특별한 경우를 제외하면 대부분 싱글톤을 사용함
  • 의존 관계 설정
    • 생성자에 @Autowired 를 사용하면 객체 생성 시점에 스프링 컨테이너에서 해당 스프링 빈을 찾아서 주입함
    • 생성자가 1개만 있으면 @Autowired 생략 가능
    • @Autowired 를 통한 DI는 스프링이 관리하는 객체에서만 동작함
    • 스프링 빈으로 등록하지 않고 내가 직접 생성한 객체에서는 동작하지 않음

 

7) DB 접근 기술

  • 데이터 저장소 선정 후 클래스 간 의존관계 및 스프링 설정 관계



① 순수 Jdbc

//build.gradle
// => jdbc, h2 데이터베이스 관련 라이브러리 추가
dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'org.jetbrains:annotations:23.0.0'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	runtimeOnly('org.springframework.boot:spring-boot-devtools')

	// jdbc 관련 라이브러리 추가 - 순수 Jdbc, 스프링 JdbcTemplate
	implementation 'org.springframework.boot:spring-boot-starter-jdbc'

	// h2 데이터베이스 관련 라이브러리 추가
	runtimeOnly 'com.h2database:h2'

	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

//resources/application.properties
// => 스프링 부트 데이터베이스 연결 설정 추가
spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa

//Jdbc 리포지토리 구현
// ...

 

② 스프링 JdbcTemplate

  • 순수 Jdbc와 동일한 환경설정
  • 참고로 스프링 JdbcTemplateMyBatis 같은 라이브러리는 JDBC API에서 본 반복 코드를 대부분 제거해주지만 SQL은 직접 작성해야함

③ JPA

  • 기존의 반복 코드는 물론이고, 기본적인 SQL도 JPA가 직접 만들어서 실행해줌
  • SQL과 데이터 중심의 설계에서 객체 중심의 설계로 패러다임을 전환할 수 있음
  • 개발 생산성을 크게 높여줌
//build.gradle
// => JPA, h2 데이터베이스 관련 라이브러리 추가
dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'org.jetbrains:annotations:23.0.0'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	runtimeOnly('org.springframework.boot:spring-boot-devtools')

	// jdbc 관련 라이브러리 추가 - 순수 Jdbc, 스프링 JdbcTemplate
	//implementation 'org.springframework.boot:spring-boot-starter-jdbc'

	// h2 데이터베이스 관련 라이브러리 추가
	runtimeOnly 'com.h2database:h2'

	// JPA 관련 라이브러리 추가 - Jpa
	// => 스프링 부트가 자동으로 EntityManager 객체(JPA를 동작하게 하는 관리 객체)를 생성해줌
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

//resources/application.properties
// => 스프링 부트 JPA 설정 추가
spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa

//JPA
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
##spring.jpa.hibernate.ddl-auto=create


//JPA 엔티티 매핑
//...

//JPA 회원 리포지토리
//...

//서비스 계층에 트랜잭션 추가
// => JPA를 통한 모든 데이터 변경은 트랜잭션 안에서 실행해야 한다.

 

④ 스프링 데이터 JPA

    • JPA와 동일한 환경설정
    • 스프링 데이터 JPA를 사용하면 리포지토리에 구현 클래스 없이 인터페이스 만으로 개발을 완료할 수 있음
    • 그리고 반복 개발해온 기본 CRUD 기능도 스프링 데이터 JPA가 모두 제공함
    • 조금이라도 단순하고 반복이라 생각했던 개발 코드들이 확연하게 줄어듬
    • 개발자는 핵심 비즈니스 로직을 개발하는데 집중할 수 있음
    • 관계형 데이터베이스를 사용한다면 스프링 데이터 JPA는 이제 선택이 아니라 필수

8) AOP

  • 관점 지향 프로그래밍
  • 공통 관심 사항(cross-cutting concern) vs 핵심 관심 사항(core concern)
반응형