스프링 입문 Section1. 프로젝트 환경설정

Bae YuSeon·2024년 4월 10일
1

spring스터디

목록 보기
1/15
post-thumbnail

1. 프로젝트 생성

사전 준비물

⚠️스프링 부트 3.0 이상, JDK 17 이상을 사용!

스프링 부트 스타터 Spring initializar
스프링 부트 스타터 사이트 (스프링 부트 기반으로 스프링 관련 프로젝트를 만들어 주는 사이트) 를 사용해 스프링 프로젝트를 생성


Project

  • maven: 내가 사용할 라이브러리 뿐만 아니라 해당 라이브러리가 작동하는데 필요한 다른 라이브러리들까지 관리하여 네트워크를 통해 자동으로 다운 받아줌
  • gradle: 기본적으로 빌드 배포 도구(Build Tool). JAVA, C/C++, Python 등을 지원

⇒ 요즘은 maven보다 gradle을 많이 사용하는 추세
참고 링크


Spring Boot

  • SNAPSHOT은 아직 만들고 있는 버전
  • M3는 정식으로 릴리즈 되지 않은 버전

⇒ 정식 버전 중에 가장 버전이 높은 것을 선택


Project MetaData는 아래처럼 작성


Dependencies은 Spring Web과 Thymeleaf를 선택


이렇게 설정을 다 한 후에 generate 버튼 클릭해서 프로젝트 다운받기

다운 받은 프로젝트는 원하는 폴더에 압축 풀기


다운 받은 프로젝트를 실행하기 위해

IntelliJ를 열어 open or import를 클릭하고 압축을 풀어놓은 폴더의 builg.gradle을 선택한다.

OK → open as project


  • src폴더 안에 main과 test폴더가 있다.
    • main폴더 안에는 java와 resources폴더가 있다.
    • test폴더 안에는 test코드와 관련된 파일들이 들어있다.
  • java폴더 안에는 실제 소스파일과 패키지가 있다.
  • resources폴더 안에는 실제 java코드 파일을 제외한 xml, html 등 설정파일들이 있다.

자동 생성된 gradle 설정 파일 확인


//프로젝트에 필요한 gradle 플러그인 선언 
//(선택한 버전 설정, 라이브러리 가져옴)
plugins {
	id 'java'
	id 'org.springframework.boot' version '3.2.4'
	id 'io.spring.dependency-management' version '1.1.4'
}

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'
}

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

자동생성된 mainApplicaiton.java 파일 확인


@SpringBootApplication
public class HelloSpringApplication {

	public static void main(String[] args) {
		
		SpringApplication.run(HelloSpringApplication.class, args);
	}

}

프로젝트 실행
main/java/spring/hellospring/HelloSpringApplication.java 파일을 선택하여 main 함수 실행

8080 포트로 tomcat이 연결되었다는 결과

http://localhost:8080 페이지로 들어가면

이런 에러 메시지가 뜨는데 환경 설정에 성공한 것이다!

  • IntelliJ Gradle 대신에 자바 직접 실행
    ctrl + alt + s를 입력하여 setting에 가서 빌드 도구를 gradle에서 IntelliJ로 바꾸기

2. 라이브러리 살펴보기

스프링 부트 라이브러리

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

프로젝트를 만들면서 라이브러리로 Spring Web, Thymeleaf만 가져왔지만 실제로는 아주 많은 라이브러리를 가져오게 된다.
⇒ Gradle은 의존관계가 있는 라이브러리를 함께 다운로드 하기 때문

오른쪽 상단에 있는 코끼리 이모티콘의 Gradle 버튼을 누르면 내가 사용하고 있는 라이브러리들의 의존관계를 확인할 수 있다.

3. View 환경설정

정적 페이지 만들기

아까 전에 http://localhost:8080 페이지에 아무 것도 만들어 있지 않아 error가 떴었다. 이제 페이지를 직접 만들기 위헤 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>

index.html을 작성한 후 다시 프로젝트를 실행하여 http://localhost:8080에 들어가면 아래와 같은 화면이 뜬다.

스프링 부트에서 제공하는 Welcome Page 기능: static/index.html을 올려두면 Welcome page로 제공
spring boot features doc

동적 페이지 만들기
⇒ thymeleaf 템플릿 엔진
thymeleaf 공식 사이트
src → main → java → hellospring 폴더 밑에 controller 라는 패키지를 만들고 그 안에 HelloController 라는 java class 파일을 만든다.

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!!");
        // attribute 의 이름이 "data"인 곳에 value 로 "hello!!" 가 들어감
        return "hello";
    }
}

src → main → resources → template 밑에 hello.html 파일을 새로 만든다.

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org"> <!--템플릿 엔진으로 thymeleaf 사용할 수 있게 함-->
<head>
    <title>Hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>

작성 후에 다시 프로젝트를 실행하면 http://localhost:8080/hello 페이지에 들어가면
${data} 자리에 hello!! 가 들어간 것을 확인할 수 있다.

동작 원리

  • 컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버( viewResolver )가 화면을 찾아서 처리한다.
    • 스프링 부트 템플릿엔진 기본 viewName 매핑
    • resources:templates/ +{ViewName}+ .html

4. 빌드하고 실행하기

윈도우 사용자

  • 콘솔로 이동 명령 프롬프트(cmd)로 이동
    → ./gradlew gradlew.bat 를 실행
  • 명령 프롬프트에서 gradlew.bat 를 실행하려면 gradlew
  • gradlew build
  • 폴더 목록 확인 ls dir

0개의 댓글

관련 채용 정보