김영한님의 인프런 강의 "스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술"의 강의 내용을 복습하며 기록한 내용입니다.
스프링을 왜 공부해야 하는가?
실무에서 제대로 동작하는 웹 어플리케이션을 개발하기 위해서!
간단한 웹 어플리케이션 개발
프로젝트 생성
사전 준비물
스프링 부트 스타터 사이트로 이동해서 스프링 프로젝트 생성
https://start.spring.io
참고: 스프링 입문 강좌 velog
선택을 마치고 Generate를 클릭하면 프로젝트가 zip 파일 형태로 다운 받아진다.
이제 프로젝트의 실체를 보기 위해 압축을 해제하고 원하는 폴더에 넣은 후 IntelliJ에서 임포트를 하도록 하자.
Intellij에서 Open or Import를 클릭 한 후 다운받은 프로젝트 폴더로 찾아가 build.gradle
파일을 열어준다.
src/main/java
: 비즈니스 로직 구현을 할 Java 파일hello.hellospring
은 패키지src/main/resources
: 그 외 화면을 구성할 HTML/CSS/JS 혹은 설정 파일 등src/test
: test와 관련된 코드윈도우 사용자 File -> Setting
build.gradle
plugins {
id 'org.springframework.boot' version '2.6.4'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'hello'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
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'
}
tasks.named('test') {
useJUnitPlatform()
}
HelloSpringApplication.java
package hello.hellospring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloSpringApplication {
public static void main(String[] args) {
SpringApplication.run(HelloSpringApplication.class, args);
}
}
main
메소드를 실행하면 SpringApplication.run()
에서 HelloSpringApplication
클래스를 넣어주면, @SpringBootApplication
어노테이션으로 인해 스프링부트어플리케이션이 실행됨실행: localhost:8080
라이브러리 살펴보기
Gradle은 의존관계가 있는 라이브러리를 함께 다운로드 한다.
Intellij 우측 상단에 Gradle을 누르면 Dependencies를 누르면 확인할 수 있다.
System.out.println
보다 log를 씀View 환경설정
static/index.html
을 올려두면 Welcome page 기능을 제공한다.resources/static
에서 index.html
을 찾고, 없으면 index
템플릿을 찾는다.<!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>
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";
}
}
GetMapping
: 웹 어플리케이션에서 /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>
<html xmlns:th="http://www.thymeleaf.org">
: 템플릿 엔진으로서 thymeleaf 문법을 쓸 수 있다.viewResolver
)가 화면을 찾아서 처리한다.resources:templates/ +{ViewName}+ .html
hello.html
을 처리참고:
spring-boot-devtools
라이브러리를 추가하면,html
파일을 컴파일만 해주면 서버 재시작 없이
View 파일 변경이 가능하다.
인텔리J 컴파일 방법: 메뉴 build Recompile
빌드하고 실행하기
콘솔로 이동
./gradlew build
cd build/libs
java -jar hello-spring-0.0.1-SNAPSHOT.jar
윈도우 사용자를 위한 팁
./gradlew
-> gradlew.bat
를 실행하면 됩니다.gradlew.bat
를 실행하려면 gradlew
하고 엔터를 치면 됩니다.gradlew build
cd build/libs
폴더의 .jar
파일만 복사해서 서버에서 넣어주고 java -jar 해서 실행시킴 -> 서버에서도 spring 동작