• Feed
  • Explore
  • Ranking
/
/
    Spring

    [Spring Boot] Ch 1. 프로젝트 환경설정

    스프링 공부 내용 정리
    스프링Spring스프링 부트Spring Boot
    전
    전병우
    2024.05.23
    ·
    5 min read

    1. 프로젝트 생성


    "스프링 부트 스타터 사이트를 이용해 프로젝트 생성"
    https://start.spring.io

    • 프로젝트 선택

      • Project: Gradle Project

      • Spring Boot: 3.2.5

      • Packaging: Jar

      • Java: 17

    • Project Metadata

      • Group: demo

      • Artifact: demo

    • Dependencies: Spring Web, Thymeleaf

    선택을 마친 후 Generate 를 클릭하면 zip파일 형태로 다운받아진다. 프로젝트의 실체를 보기 위해서는 압축을 해제하고 원하는 폴더에 넣은 후 IntelliJ에서 Import를 해야 한다.
    Import 방법: Open or Import 클릭 → 다운받은 프로젝트 폴더로 찾아가 build.gradle 파일 열기

    "Gradle 전체 설정"
    build.gradle

    plugins {
    	id 'java'
    	id 'org.springframework.boot' version '3.2.5'
    	id 'io.spring.dependency-management' version '1.1.4'
    }
    
    group = 'com.example'
    version = '0.0.1-SNAPSHOT'
    
    java {
    	sourceCompatibility = '17'
    }
    
    repositories {
    	mavenCentral()
    }
    
    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'
    	compileOnly 'org.springframework.boot:spring-boot-devtools'
    }
    
    tasks.named('test') {
    	useJUnitPlatform()
    }
    • 동작 확인

      • 기본 메인 클래스 실행

      • 스프링 부트 메인 실행 후 에러페이지로 간단하게 동작 확인(http://localhost:8080 )

    IntelliJ Gradle 대신에 자바 직접 실행

    최근 IntelliJ 버전은 Gradle을 통해서 실행 하는 것이 기본 설정이다. 이렇게 하면 실행속도가 느리다. 다음과 같이 변경하면 자바로 바로 실행해서 실행속도가 더 빠르다.

    • Preferences → Build, Execution, Deployment → Build Tools → Gradle

      • Build and run using: Gradle → IntelliJ IDEA

      • Run tests using: Gradle → IntelliJ IDEA

    2. 주요 라이브러리 살펴보기

    Gradle은 의존관계가 있는 라이브러리를 함께 다운로드 한다. 때문에 Spring Web이랑 Thymeleaf 겨우 2개 추가했을 뿐인데 정말 많은 라이브러리들이 꽉꽉 들어차있는 것을 볼 수 있다. 이처럼 물밑에서는 수많은 라이브러리들은 서로가 서로를 의존하고 있는데, Gradle은 개발자가 그 모든 라이브러리들을 일일이 추가할 필요없이 '사용하겠다'라고 선언만 해주면 알아서 필요한 것들을 가져와 설치해준다.

    "스프링 부트 라이브러리"

    • spring-boot-starter-web

      • spring-boot-starter-tomcat: 톰캣 (웹서버)

      • spring-webmvc: 스프링 웹 MVC

    • spring-boot-starter-thymeleaf: 타임리프 템플릿 엔진(View)

    • spring-boot-starter(공통): 스프링 부트 + 스프링 코어 + 로깅

      • spring-boot

        • spring-core

      • spring-boot-starter-logging

        • logback, slf4j

    “테스트 라이브러리”

    • spring-boot-starter-test

      • junit: 테스트 프레임워크

      • mockito: 목 라이브러리

      • assertj: 테스트 코드를 좀 더 편하게 작성하게 도와주는 라이브러리

      • spring-test: 스프링 통합 테스트 지원

    3. View 환경설정

    Welcome Page 만들기

    resources/static/index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Welcome Page</title>
    </head>
    <body>
        Hello, This is Welcome Page.
    </body>
    </html>
    • 스프링 부트가 제공하는 Welcome Page 기능

      • static/index.html 을 올려두면 Welcome Page 기능을 제공한다.

    • thymeleaf 템플릿 엔진

      • thymeleaf 공식 사이트: https://www.thymeleaf.org/

      • 스프링 공식 튜토리얼: https://spring.io/guides/gs/serving-web-content/

    demo/controller/HelloController

    package com.example.demo.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    
    @Controller
    public class HelloController {
    
        @GetMapping("hello")
        public String hello(Model model) {
            model.addAttribute("name", "전병우");
            return "about-me";
        }
    
    }
    

    resources/templates/about-me.html

    <!DOCTYPE html>
    <html lang="ko" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>About Me</title>
    </head>
    <body>
        <p th:text="'안녕하세요. 저는 ' + ${name} + '입니다.'"></p>
    </body>
    </html>

    "thymeleaf 템플릿엔진 동작 확인"
    http://localhost:8080/hello

    "동작 흐름 그림"

    until-307
    • 컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버(viewResolver)가 화면을 찾아서 처리한다.

      • 스프링 부트 템플릿엔진 기본 viewName 매핑

      • resources:templates/ + (ViewName) + .html

    참고: spring-boot-devtools 라이브러리를 추가하면, html 파일을 컴파일만 해주면 서버 재시작 없이 View 파일 변경이 가능하다.
    IntelliJ 컴파일 방법: 메뉴 build → Recompile

    4. 빌드하고 실행하기

    터미널로 이동
    1. ./gradlew build --scan
    2. cd build/libs
    3. java -jar demo-0.0.1-SNAPSHOT.jar
    4. 실행 확인







    - 컬렉션 아티클