Light Blue Pointer
본문 바로가기
Developing/TIL(Develop)

첫 실습! HelloWorld GET해오기 with SpringBoot + Postman

by Greedy 2023. 11. 1.

1. 깃과 인텔리제이 설정

우선 깃과 인텔리제이를 설치해줌

인텔리제이에서 

Auto import 설정

setting → Editor → General → Auto import → Add unambiguous imports on the fly , Optimize imports on the fly , Always 에 체크함

 

Git Repository 생성하기

최상단의 프로젝트를 파랗게 되게 클릭 후 VCS → Create Git Repository

 

Gradle이란?

빌드 자동화 시스템

자바 코드를 설정에 맞게 자동으로 빌드해줌

Build

소스코드를 실행 가능한 결과물로 만드는 일련의 과정

 

 

우측 탭 Gradle → Tasks→ build → build 클릭

왼쪽 탭 project → build → libs(libraries) → projectname-0.0.1-SNAPSHOT.jar 실행가능한 파일로 만들어서 넣어뒀대

왼쪽 탭 project → build.gradle / 오른쪽 탭 gradle → projectname우클릭 → open gradle config

build.gradle : gradle 기반의 build script groovy/kotlin으로 작성 가능

라이브러리 관리함

필요한 외부 라이브러리들을 dependencies부분에다가 작성하면 gradle이 해당 라이브러리를 maven repository 라는 외부 저장소에서 자동으로 다운로드 해온다 함

maven repository

라이브러리 저장소

다른 라이브러리들과의 의존성을 자동으로 관리해준다 함

라이브러리들 간의 충돌 걱정 없이 개발에만 집중할 수 있다고 함

 

gradle 파일은 이렇게 생겼다

plugins {
	id 'java'
	id 'org.springframework.boot' version '3.1.5'//앞 두개 버전에 따라 차이가 크대
	id 'io.spring.dependency-management' version '1.1.3'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'

java {
	sourceCompatibility = '17'
}

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

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

 

 

Postman

API 개발을 빠르고 쉽게 구현할 수 있도록 도와주는 소프트웨어 플랫폼 중 하나

Q. 다른 것들은 어떤 것들이 있을까?

API에 맞춰서 HTTP요청을 서버에 보내고 응답을 확인하여 서버가 제대로 동작하는지 확인하는 것을 간편하게 할 수 있도록 도와줌

 

테스트 실습

Postman 설치 : https://www.postman.com/downloads/

spring-prepare 프로젝트와 Postman을 사용하여 “Hello World!”를 출력하는 API를 만들고 테스트

API 테이블 : API들을 한눈에 확인하고 협업하는 개발자들과 소통하기 위해 작성하는 일종의 표

Name Method Url 설명

인사 Get /api/hello Hello World!를 출력
  1. API 요청을 받아서 처리하기 위해 HelloController를 만듦
  2. Postman을 사용하여 API를 테스트

IntelliJ Spring project에서

src → com.blah.blah → 우클릭 →new → package

main.java.com.example.springprepare.controller 생성해줌

(package가 선택지에 안 뜨면 src 우클릭 후 mark directory as source)

@RestController

하고 엔터 치면 자동으로 import된대

 

문제 발생 : 

빨간줄이 뜨는데요…

살랴주세요

 

구글링해봄

스프링 어노테이션들을 인식을 못한다는 것은 결국은 라이브러리(dependencies)들이 제 기능을 못한다는 것이므로 인텔리제이 기준으로 build.gradle에서 빨간 박스의 돌고래 표시(Load Gradle Changes) (단축키 ctrl + shift + O)를 눌러준다. 저 표시는 라이브러리들이나 환경세팅이 변경됐을 경우 그 세팅에 맞게 프로젝트를 설정해주는 기능이다.

spring-web을 임시로 주석처리하여 리로딩해주면 변화가 발생했기 때문에 인텔리제이에서 빨간박스에 보이는 것처럼 리로딩할 세팅에 맞게 라이브러리들을 다운받는다.

그 다음에 다시 spring-web 주석을 해제하여 돌고래 표시를 눌러주어 리로딩해준다.

블로그에서 implementation 'org.springframework.boot:spring-boot-starter-web' 이걸 주석처리했다가 풀라고 하는데 나는 아예 없어서 dependencies에 넣어줬다

implementation 'org.springframework.boot:spring-boot-starter'

그리고 이걸 지워봄

여전히 안 됨

java.lang.IllegalStateException: Module entity with name: spring-prepare should be available

지금보니 이렇게 에러가 나고 있었음

 

구글링해봄

실제 프로젝트명과 setting.gradle의 rootProject.name을 일치시켜 주었더니 바로 해결되었다.

반드시 대/소문자를 맞춰주자

만들때 spring-prepare로 하다가 Springprepare로 바꿨었음

그래서 java.com.example.springprepare→Springprepare로 바꿔봄

응 역시 안 된다

포기하고 그냥 프로젝트 새로 만듦

만들때 dependencies에 web 추가해봄 전에 아무것도 안 추가한 거 같아서

 

이번에는 이렇게 나옴

• No matching variant of org.springframework.boot:spring-boot-gradle-plugin:3.1.5 was found. The consumer was configured to find a library for use during runtime, compatible with Java 8, packaged as a jar, and its dependencies declared externally, as well as attribute 'org.gradle.plugin.api-version' with value '8.3' but:

이 문제를 구글링해봤더니

Solved after changing Gradle JVM version to 17 in IntelliJ.

Ctrl + Alt + S > Build, Execution, Deployment > Gradle > Gradle JVM -> java 17

이렇게 나옴

Java home 으로 되어있는거 corretto-17로 바꿈

해결됨

Q. JDK21 아니면 다 Amazon corretto로 뜨는거 왜 그런거지?

 

첫 API를 만들어봄!

package com.example.helloworld.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @GetMapping("/api/hello")
    public String hello(){
        return "Hello World!";
    }
}

~Application을 Run 하면 다음과 같이 나옴

 

. ____ _ __ _ _ /\\ / ' __ _ () __ __ _ \ \ \ \ ( ( )\__ | '_ | '| | ' \/ ` | \ \ \ \ \\/ )| |)| | | | | || (| | ) ) ) ) ' || .__|| ||| |\, | / / / / =========||==============|/=///_/ :: Spring Boot :: (v3.1.5)

2023-11-01T16:35:22.948+09:00 INFO 11712 --- [ main] c.e.helloworld.HelloworldApplication : Starting HelloworldApplication using Java 17.0.9 with PID 11712 (E:\Workspace\IntelliJ\helloworld\build\classes\java\main started by USER in E:\Workspace\IntelliJ\helloworld) 2023-11-01T16:35:22.952+09:00 INFO 11712 --- [ main] c.e.helloworld.HelloworldApplication : No active profile set, falling back to 1 default profile: "default" 2023-11-01T16:35:24.085+09:00 INFO 11712 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2023-11-01T16:35:24.097+09:00 INFO 11712 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2023-11-01T16:35:24.097+09:00 INFO 11712 --- [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.15] 2023-11-01T16:35:24.219+09:00 INFO 11712 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2023-11-01T16:35:24.220+09:00 INFO 11712 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1184 ms 2023-11-01T16:35:24.816+09:00 INFO 11712 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2023-11-01T16:35:24.828+09:00 INFO 11712 --- [ main] c.e.helloworld.HelloworldApplication : Started HelloworldApplication in 2.584 seconds (process running for 3.795)

 

 

Postman 사용방법

  1. Workspaces 에서 워크 스페이스를 만들고 ‘New’를 클릭
  2. HTTP Request를 클릭
  3. GET 방식을 선택하고 http://localhost:8080/api/hello URL을 입력하고 ‘Send’를 클릭
  4. API 요청이 우리가 만든 서버에서 처리되어 “Hello World!” 문자열이 출력된 것을 아래 Body 탭에서 확인할 수 있다.
  5. Tomcat started on port(s): 8080 (http) with context path → Tomcat은 기본적으로 8080포트로 실행시킨다고 함

Hello World! 가 body에 출력된다!

 

commit 하려고 하니까 이게 뜸

https://www.jetbrains.com/help/idea/set-up-a-git-repository.html

Define a remote

  1. Create an empty repository on any Git hosting, such as Bitbucket or GitHub. You can create a repository on GitHub without leaving IntelliJ IDEA: see Share a project on GitHub.
  2. Invoke the Push dialog when you are ready to push your commits by selecting Git | Push from the main menu, or press CtrlShift0K.
  3. If you haven't added any remotes so far, the Define remote link will appear instead of a remote name. Click it to add a remote.
  4. In the dialog that opens, specify the remote name and the URL where it will be hosted, and click OK

깃허브에 repository 생성하고 그거 URL 넣었더니 push되었음

https://github.com/minisundev/HelloWorld

 

GitHub - minisundev/HelloWorld: My first API

My first API. Contribute to minisundev/HelloWorld development by creating an account on GitHub.

github.com