[Spring] 스프링 입문 - 프로젝트 환경설정

진기·2024년 5월 29일


프로젝트 환경설정

프로젝트 생성

  • Java 17.0.10

  • IDE : IntelliJ

    스프링 부트 스타터 사이트로 스프링 프로젝트 생성하기 : https://start.spring.io

  • 프로젝트 선택

    • Project: Gradle - Groovy Project Spring Boot: 3.x.x
    • Language: Java
    • Packaging: Jar
    • Java: 17 또는 21
  • Project Metadata

    • groupId: hello
    • artifactId: hello-spring
  • Dependencies: Spring Web, Thymeleaf

Gradle 설정

📌build.gradle 예시

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

group = 'hello'
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'
}

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

🌏 서버 구동 localhost:8080 실행 화면


라이브러리

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: 스프링 통합 테스트 지원

View 환경설정

Welcome Page 만들기

📌 스프링 부트가 제공하는 Welcome Page 기능

  • static/index.html을 올려두면 자동으로 Welcome Page 기능을 제공함

🔗 resources/static/index.html

<!DOCTYPE HTML>
<html>
<head>
    <title>Hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
Hello
<a href="/hello">hello</a>
</body>
</html>

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

템플릿 엔진 동작 확인

🔗 main/java/hello.hellospring/controller/HelloController.java

@Controller
public class HelloController {
    @GetMapping("hello")
    public String hello(Model model){
        model.addAttribute("data","hello!!");
        return "hello";
    }
}

🔗 main/resources/templates/hello.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>

동작 원리

📌 컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버(viewResolver) 가 화면을 찾아서 처리함

  • 스프링 부트 템플릿엔진 기본 viewName 매핑
  • resources:templates/ + {ViewName} + .html

참고 : spirng-boot-devtools 라이브러리를 추가하면, html 파일을 컴파일만 해주면 서버 재시작 없이 View 파일 변경 가능

profile
개발 성장 이야기

0개의 댓글