공부하는 블로그

Springboot로 REST API 시작하기 (2) - 프로젝트 실행 및 REST API 만들기 본문

스프링부트

Springboot로 REST API 시작하기 (2) - 프로젝트 실행 및 REST API 만들기

devtimothy 2018. 12. 13. 19:18

Springboot로 REST API 시작하기 (2) - 프로젝트 실행 및 REST API 만들기

프로젝트 실행

  • Ctrl + F9 단축키로 앱 실행을 해보았다.

  • 실패했다.

***************************
APPLICATION FAILED TO START
***************************
Description:Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

// application.properties

spring.datasource.url=jdbc:mysql://localhost/myapp
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  • 다시 실행해보니 또 오류가 난다. 아마 DB 설정을 mysql로 해놓고 관련 의존성을 설치하지 않아서인듯 하다.

  • gradle은 javascript 진영의 npm, yarn과 같은 패키지 매니저 역할을 담당한다. 옛날에는 maven을 많이 썼는데 요새는 gradle이 대세라고 하는 듯 하다.

  • build.gradle에 밑에 보면 dependencies가 있다. compile("mysql:mysql-connector-java:5.1.34")를 추가로 입력한다.

  • 아래 보면 Gradle projects need to be imported 라고 있다. Import Changes 를 눌러준다.

  • IntelliJ가 친절하게 의존성을 다운받는다.

  • 다시 실행한다.

  • 실패했다.

  • myapp 이라는 데이터베이스가 없어서 그런듯 하다. mysql에 myapp 이라는 데이터베이스를 생성한다.

  • 다시 실행한다.

  • main] com.example.myapp.MyappApplicationKt : Started MyappApplicationKt in 6.343 seconds (JVM running for 7.001) 메시지를 확인할 수 있다. 오! 드디어 실행이 되었다.

  • Postman을 켜서 http://localhost:8080 (GET) 을 실행해본다. 아래와 같이 응답이 왔다.

{
  "_links": {
      "profile": {
          "href": "http://localhost:8080/profile"
      }
  }
}
  • 여기까지는 잘 된 듯 하다.

REST API를 만들어보자

  • 이제 API를 만들어보자. 사실 구조를 어떻게 잡아야 하는지도 아직 잘 모르겠다.

  • com.example.myapp 패키지 내에 HomeController.kt 클래스를 생성해준다.

package com.example.myapp

import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController

@RestController
class HomeController {
   @RequestMapping(value = ["/"], method = [RequestMethod.GET])
   fun Index() : String = "Hello Spring World!"
}
  • 다시 어플리케이션을 실행시키고, Postman에서 localhost:8080 을 실행하면 Hello Spring World! 문구가 응답으로 잘 오는 것을 확인할 수 있다.

  • 간단하게 REST API가 잘 넘어옴을 확인할 수 있었다.


다음 편


Comments