스프링 입문 1일차 : 프로젝트 환경 설정
# 프로젝트 환경 설정
- 필요 도구
Java 11 설치
IDE: IntelliJ 또는 Eclipse 설치
(가급적 IntelliJ 설치)
- 스프링 부트를 기반으로 프로젝트 생성 ( start.spring.io/ )
- Maven / Gradle : 버전 설정 및 라이브러리를 가져오는 등 필요한 라이프 사이클을 관리해주는 툴 (과거엔 Maven 사용, 요즘엔 대부분 Gradle 사용)
- 위 사이트 에서 아래와 같이 선택하여 생성 진행
Project : Gradle Project
Language : Java
Spring Boot : 2.3x
Group : hello
(보통 기업명, 기업 도메인명 입력)
Artifact : hello-spring
(빌드된 결과물)
ADD DEPENDENCIES의 경우 아래 항목들 찾아서 주입
(어떤 라이브러리를 가져다가 사용할지)
- Spring Web
- Thymeleaf
- 완료 후 하단의 'GENERATE' 클릭하여 다운로드 진행.
- 원하는 경로에 다운로드 받은 압축파일의 압축 해제.
- (예) c 드라이브 내 study 등의 폴더 생성하여 안에 넣기)
- 인텔리제이 실행
인텔리제이 실행 후 Open or Import 클릭하여 압축해제한 폴더 내 build.gradle 클릭 후 Open As Project 클릭.
## build.gradle
- 위 사이트에서 설정한 항목들이 입력(주입)된 것을 확인할 수 있다.
## .gitignore
- 깃에 필요한 소스코드 파일만 올라갈 수 있도록 기본적으로 입력되어 있다.
## 프로젝트 실행
- main 프로젝트에 가서 화살표 모양 클릭하여 Run 진행
- 실행 후 http://localhost:8080/ 입력해서 페이지가 나오는지 확인 (입력된 게 없지 때문에 해당 주소로 들어가면 에러메시지가 나와있다.) (스프링부트는 웹서버(톰캣)를 내장하고 있어서 자체적으로 톰캣을 실행하면서 스프링부트가 실행된다.)
## Run 설정 변경
- file > settings 에서 gradle 입력 후 선택하여 아래와 같이 변경
Build and run using : IntelliJ IDEA
Run tests using : IntelliJ IDEA
- gradle을 통하지 않고 인텔리제이에서 자바를 바로 실행 훨씬 빠른속도로 이용할 수 있다.
# 라이브러리 살펴보기
- 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
- 현업에서 일할 경우 system.out.println 보다는 logging로 출력해야 함.
- 왼쪽 하단에 네모 > gradle 클릭 시 라이브러리 확인 가능
## 테스트 라이브러리
- spring-boot-starter-test
junit : 테스트 프레임워크
mockito : 목 라이브러리
assertj : 테스트 코드를 좀 더 편하게 작성하게 도와주는 라이브러리
spring-test : 스프링 통합 테스트 지원
# View 환경설정
## Welcome Page 생성하기
- main/java/resources/static/index.html 생성. (스프링의 경우 index.html로 생성 시 welcome page로 인식)
- index.html 에 아래와 같이 입력 (아래 입력한 내용은 정적페이지.)
<!DOCTYPE html>
<html lang="ko">
<head>
<meta http-equiv="Content-Type" content="text/html"; charset="UTF-8">
<title>Hello</title>
</head>
<body>
Hello
<a href="/hello">hello</a>
</body>
</html>
- 입력 완료 후 localhost:8080 진입 시 입력된 내용이 나오는 걸 확인 할 수 있다.
- (run 종료 후 재실행 해야한다.)
### 스프링 부트가 제공하는 Welcome Page 기능
static/index.html 을 올려두면 Welcome page 기능을 제공한다.
spring.io/에 접속, Projects 클릭 후 Spring Boot 클릭 > LEARN 클릭 > Reference.Doc 클릭 'welcome page'를 검색해 보면 welcome page에 대한 정보를 확인할 수 있다.
Spring Boot Features
Graceful shutdown is supported with all four embedded web servers (Jetty, Reactor Netty, Tomcat, and Undertow) and with both reactive and Servlet-based web applications. It occurs as part of closing the application context and is performed in the earliest
docs.spring.io
## thymeleaf 템플릿 엔진
- thymeleaf 공식 사이트: https://www.thymeleaf.org/
Thymeleaf
Integrations galore Eclipse, IntelliJ IDEA, Spring, Play, even the up-and-coming Model-View-Controller API for Java EE 8. Write Thymeleaf in your favourite tools, using your favourite web-development framework. Check out our Ecosystem to see more integrati
www.thymeleaf.org
- 스프링 공식 튜토리얼: https://spring.io/guides/gs/serving-web-content/
Serving Web Content with Spring MVC
this guide is designed to get you productive as quickly as possible and using the latest Spring project releases and techniques as recommended by the Spring team
spring.io
- 스프링부트 메뉴얼: https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/html/spring-boot-features.html#boot-features-spring-mvc-template-engines
- controller 생성 (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";
}
}
- 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>
### thymeleaf 템플릿엔진 동작 확인 실행: http://localhost:8080/hello
- 컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버( iewResolver)가 화면을 찾아서 처리한다.
스프링 부트 템플릿엔진 기본 viewName 매핑
resources:templates/ +{ViewName}+ .html
- 참고 : spring-boot-devtools 라이브러리를 추가하면, html 파일을 컴파일만 해주면 서버 재시작 없이 View 파일 변경이 가능하다.
- 인텔리J 컴파일 방법 : 메뉴 build Recompile
# 빌드하고 실행하기
- 콘솔로 이동 (윈도우의 경우 cmd)
- cd study (폴더 진입) > dir (폴더 내 파일 목록 확인) > cd hello-spring > dir
콘솔로 이동 명령 프롬프트(cmd)로 이동
./gradlew gradlew.bat 를 실행하면 됩니다.
명령 프롬프트에서 gradlew.bat 를 실행하려면 gradlew 하고 엔터를 치면 됩니다.
gradlew build
폴더 목록 확인 ls dir
윈도우에서 Git bash 터미널 사용하기
링크: https://www.inflearn.com/questions/53961
출처 : 인프런 스프링 입문