본문 바로가기
Back-end/Spring

[Spring] 프로젝트 환경설정

by 안녕주 2021. 7. 26.

스프링 입문강의를 들으면서 복습겸 기록을 합니다.

 

프로젝트 생성

사전 준비물

  • Java 11설치
  • IDE : IntelliJ 또는 Eclipse 설치

스프링 부터 스타터 사이트에 가서 아래의 설정대로 스프링 프로젝트생성

https://start.spring.io

SpringBoot 프로젝트 만들기
IntelliJ에서 파일 열기
IntelliJ 설정 - gradle - Build and run using부분과 그 아래까지


라이브러리 살펴보기

IntelliJ에서 Command 두번 누르면 오른쪽 에 Gradle이 뜬다

더보기

Gradle은 의존관계가 있는 라이브러리를 함께 다운로드 한다.

그 Dependecies를 보면 라이브러리들을 볼 수 있다

 

현업에서는 System.out.println을 쓰지 않고 log를 쓴다.

log 관련 파일

test할 때는 junit 라이브러리을 사용한다.

 

* 스프링부트 라이브러리

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

1. welcome page 만들기

  •  main/resources/static/index.html
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
Hello
<a href="/hello">hello</a>
</body>
</html>

 

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

 

3. thymeleaf 템플릿 엔진

 

4. thymeleaf 템플릿엔진 동작 확인

  • 실행 : http://localhost:8080/hello
  • main/resources/templates/hello.html
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Hello</title>
</head>
<body>

<p th:text="'안녕하세요. ' + ${data}"> 안녕하세요. 손님</p>

</body>
</html>
  • main/java/hello.hellospring/controller/HelloController 
package hello.hellospring.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";
    }
}

localhost:8080/hello
동작 환경 그림

  • 컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버('viewResolver')가 화면을 찾아서 처리한다.
    • 스프링 부트 템플릿엔진 기본 viewName 매핑
    • 'resources:templates/' + {ViewName} + '.html'
참고 : 'spring-boot-devtools' 라이브러리를 추가하면, 'html'파일을 컴파일만 해주면 서버 재시작 없이 View 파일 변경이 가능하다.
IntelliJ 컴파일 방법 : 메뉴 build -> Recompile

빌드하고 실행하기

terminal에서 gredlew가 있는곳으로 이동 

1. './gradlew build'

2. 'cd build/libs'

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

4. 실행 확인

 

댓글