본문 바로가기
Spring

[Spring] Spring Boot 프로젝트 생성, 실행, 빌드하기

by jelliclesu 2024. 9. 4.

프로젝트 생성하기

✔️IDE: IntelliJ

 

스프링 부트 스타터 사이트로 스프링 프로젝트 생성

https://start.spring.io

  • 프로젝트 선택
    • Project: Gradle - Groovy
    • Spring Boot: 3.3.3
    • Language: Java
  • Metadata
    • Group: hello
    • Artifact: hello-spring
  • Dependencies
    • Spring Web
    • Thymeleaf(html을 만들어주는 템플릿 엔진)
더보기

Group - 기업명, 기업 도메인명 / Artifact - 빌드되면 나오는 결과물 = 프로젝트명

 

  • GENERATE > 압축 파일 풀기 > IntelliJ에서 파일 Open

 

프로젝트 실행 및 빌드

동작 확인

  • 기본 메인 클래스 실행
    - @SpringBootApplication: 스프링부트 애노테이션으로 톰캣이라는 웹서버를 내장하고 있어서 스트링부트 실행
    - 스프링부트 스타터 사이트에서 프로젝트를 생성하면 @SpringBootApplication 이 작성된 상태로 프로젝트가 생성됨 

실행 로그에서 Tomcat 실행 확인 가능

 

  • http://localhost:8080로 이동하여 에러페이지로 간단하게 동작 확인


✚ IntelliJ로 자바 직접 실행

  • Gradle을 통해 실행하는 것이 기본 설정인데 이렇게 하면 실행속도가 느리므로 변경해주기
  • preferences > gradle > Build and run using, Run tests using -> IntelliJ IDEA 로 설정

 


✚ 라이브러리 살펴보기

  • 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 환경설정

Welcom Page 만들기

  • src > main > 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>

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

 

  •  java > hello.hello_spring > controller 패키지 생성 > helloController.java 생성
package hello.hello_spring.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("data", "hello!!");
        return "hello";
    }

}

 

 

  • 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>

 

- data : model 에서의 key 값 (즉, hello!!)

 

 

동작 환경 그림

return:hello - templates 밑의 hello를 찾아서 랜더링

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

- 스프링 부트 템플릿 엔진 기본 veiwName 매핑

- resource:templates/ + {ViewName} + .html


프로젝트 빌드하고 실행하기

  • 콘솔로 이동
./gradlew build

cd build/libs

java -jar hello-spring-0.0.1-SNAPSHOT.jar

 

  • 실행 확인하기