Spring01 프로젝트 환경설정

6 minute read

Spring 프로젝트 환경설정

프로젝트 생성

  • 사전 준비물
    • Java 11
    • IntelliJ 또는 Eclipse
  • 스프링 부트 스타터 사이트로 이동해서 스프링 프로젝트 생성
    • https://start.spring.io
  • 프로젝트 선택
    • Project : Gradle
    • Spring Boot : 2.3.x
    • Language : java
    • Packaging : Jar
    • Java : 11
  • Project Metadata
    • Groupid : hello
    • Artifactid : hello-spring
  • Dependencies : Spring Web, Thymeleaf
  • 구조
    • hello-spring
      • .gradle
      • .idea // 인텔리제이가 사용하는 설정파일
      • gradle // 그레이들이 쓰는 폴더
      • Wrapper
      • src
        • main
          • java
          • resources // 실제 자바 파일 제외한 파일
        • test // 테스트 관련 코드
      • .gitignore // 필요 없는 파일이 올라가지 않도록 설정
      • build.gradle
      • gradlew
      • gradlew.bat
      • settings.gradle
    • External libraries // 외부 라이브러리

‘Gradle’ 전체 설정

//build.gradle

plugins {
	id 'org.springframework.boot' version '2.3.7.RELEASE'
	id 'io.spring.dependency-management' version '1.0.10.RELEASE'
	id 'java'
}

group = 'hello'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11' // 자바 버젼

repositories {
	mavenCentral() // 라이브러리를 여기서 다운받는다.
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' // html 템플릿 엔진
	implementation 'org.springframework.boot:spring-boot-starter-web'
	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

test {
	useJUnitPlatform()
}
  • main을 실행시켰을 때
> Task :HelloSpringApplication.main()

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.7.RELEASE)

2021-01-11 16:11:58.409  INFO 2852 --- [           main] h.hellospring.HelloSpringApplication     : Starting HelloSpringApplication on rsh.local with PID 2852 (/Users/rsh/study/hello-spring/build/classes/java/main started by rsh in /Users/rsh/study/hello-spring)
2021-01-11 16:11:58.415  INFO 2852 --- [           main] h.hellospring.HelloSpringApplication     : No active profile set, falling back to default profiles: default
2021-01-11 16:12:00.296  INFO 2852 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-01-11 16:12:00.323  INFO 2852 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-01-11 16:12:00.323  INFO 2852 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.41]
2021-01-11 16:12:00.675  INFO 2852 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-01-11 16:12:00.675  INFO 2852 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2155 ms
2021-01-11 16:12:01.163  INFO 2852 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2021-01-11 16:12:01.464  INFO 2852 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-01-11 16:12:01.485  INFO 2852 --- [           main] h.hellospring.HelloSpringApplication     : Started HelloSpringApplication in 3.817 seconds (JVM running for 4.498)
  • 톰캣을 내장하고 있다

라이브러리 살펴보기

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

  • 스프링 부트 라이브러리
    • Spring.boot-starter.web
      • Spring-boot-sstarter-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-text
      • junit : 테스트 프레임워크
      • mockito : 목 라이브러리
      • assertj : 테스트 코드를 좀 더 편하게 작성하게 도와주는 라이브러리
      • spring-test : 스프링 통합 테스트 지원

View 환경설정

  • welcome page 만들기
    • 도메인을 치면 맨 처음 나오는 페이지
<!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 기능
    • Static/index.html을 올려두면 welcome page 기능을 제공한다.

    • 7.1.6. Welcome Page

      Spring Boot supports both static and templated welcome pages. It first looks for an index.html file in the configured static content locations. If one is not found, it then looks for an index template. If either is found, it is automatically used as the welcome page of the application.

    • https://docs.spring.io/spring-boot/docs/2.3.7.RELEASE/reference/html/spring-boot-features.html#boot-features-spring-mvc-welcome-page (내가 쓰는 스프링부트)

    • Https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/html/spring-boot-features.html#boot-features-spring-mvc-welcome-page (강사가 쓰는 스프링부트)
  • thymeleaf 템플릿 엔진

    • 공식 사이트 : https://www.thymeleaf.org/
    • 스프링 공식 튜토리얼 : https://spring.io/guides/gs/serving-web-content/
    • 스프링부트 매뉴얼 : https://docs.spring.io/spring-boot/docs/2.3.7.RELEASE/reference/html/spring-boot-features.html#boot-features-spring-mvc-template-engines (내가 쓰는 스프링부트)
    • 스프링부트 매뉴얼 : https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/html/spring-boot-features.html#boot-features-spring-mvc-template-engines (강사가 쓰는 스프링부트)

스크린샷 2021-01-11 오후 4.42.43.png

// 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
    • 동작 환경 그림

스크린샷 2021-01-11 오후 4.46.37.png

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

빌드하고 실행하기

  • 콘솔로 이동
    • ./gradlew.build
    • cd build/libs
    • java -jar hello-spring-0.0.1-SNAPSHOT.jar
    • 실행확인
Last login: Sun Jan 10 13:38:55 on console
 rsh@rsh  ~
 cd study 
 rsh@rsh  ~/study
 cd hello-spring 
 rsh@rsh  ~/study/hello-spring
 ll 
total 48
-rw-r--r--@ 1 rsh  staff   1.4K  1 11 07:00 HELP.md
drwxr-xr-x  6 rsh  staff   192B  1 11 16:11 build
-rw-r--r--@ 1 rsh  staff   581B  1 11 07:00 build.gradle
drwxr-xr-x@ 3 rsh  staff    96B  1 11 07:00 gradle
-rwxr-xr-x@ 1 rsh  staff   5.6K  1 11 07:00 gradlew
-rw-r--r--@ 1 rsh  staff   2.7K  1 11 07:00 gradlew.bat
drwxr-xr-x  3 rsh  staff    96B  1 11 16:15 out
-rw-r--r--@ 1 rsh  staff    34B  1 11 07:00 settings.gradle
drwxr-xr-x@ 4 rsh  staff   128B  1 11 07:00 src
 rsh@rsh  ~/study/hello-spring
 ./gradlew build

Welcome to Gradle 6.7.1!

Here are the highlights of this release:
 - File system watching is ready for production use
 - Declare the version of Java your build requires
 - Java 15 support

For more details see https://docs.gradle.org/6.7.1/release-notes.html


> Task :test
2021-01-11 16:55:38.951  INFO 3163 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

BUILD SUCCESSFUL in 16s
5 actionable tasks: 5 executed
 rsh@rsh  ~/study/hello-spring
 cd build
 rsh@rsh  ~/study/hello-spring/build
 ll
total 0
drwxr-xr-x  3 rsh  staff    96B  1 11 16:11 classes
drwxr-xr-x  3 rsh  staff    96B  1 11 16:11 generated
drwxr-xr-x  3 rsh  staff    96B  1 11 16:55 libs
drwxr-xr-x  3 rsh  staff    96B  1 11 16:55 reports
drwxr-xr-x  3 rsh  staff    96B  1 11 16:11 resources
drwxr-xr-x  3 rsh  staff    96B  1 11 16:55 test-results
drwxr-xr-x  5 rsh  staff   160B  1 11 16:55 tmp
 rsh@rsh  ~/study/hello-spring/build
 cd libs
 rsh@rsh  ~/study/hello-spring/build/libs
 ls -arlth
total 35312
drwxr-xr-x  3 rsh  staff    96B  1 11 16:55 .
-rw-r--r--  1 rsh  staff    17M  1 11 16:55 hello-spring-0.0.1-SNAPSHOT.jar
drwxr-xr-x  9 rsh  staff   288B  1 11 16:55 ..
 rsh@rsh  ~/study/hello-spring/build/libs
 java -jar hello-spring-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.7.RELEASE)

2021-01-11 16:56:23.190  INFO 3219 --- [           main] h.hellospring.HelloSpringApplication     : Starting HelloSpringApplication on rsh.local with PID 3219 (/Users/rsh/study/hello-spring/build/libs/hello-spring-0.0.1-SNAPSHOT.jar started by rsh in /Users/rsh/study/hello-spring/build/libs)
2021-01-11 16:56:23.195  INFO 3219 --- [           main] h.hellospring.HelloSpringApplication     : No active profile set, falling back to default profiles: default
2021-01-11 16:56:25.152  INFO 3219 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-01-11 16:56:25.174  INFO 3219 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-01-11 16:56:25.174  INFO 3219 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.41]
2021-01-11 16:56:25.296  INFO 3219 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-01-11 16:56:25.297  INFO 3219 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1962 ms
2021-01-11 16:56:25.656  INFO 3219 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2021-01-11 16:56:25.791  INFO 3219 --- [           main] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page: class path resource [static/index.html]
2021-01-11 16:56:26.005  WARN 3219 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'webServerStartStop'; nested exception is org.springframework.boot.web.server.PortInUseException: Port 8080 is already in use
2021-01-11 16:56:26.006  INFO 3219 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2021-01-11 16:56:26.009  INFO 3219 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2021-01-11 16:56:26.028  INFO 3219 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-01-11 16:56:26.032 ERROR 3219 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Web server failed to start. Port 8080 was already in use.

Action:

Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.
  • 잘 안 되는 경우에는 ./gradlew clean build

Categories:

Updated: