Kotlin + SpringBoot로 최소 WebAPI 구축
15755 단어 spring-bootKotlin
개요
Spring 프로젝트 만들기
Spring Initializr 을 사용합니다.
IntelliJ IDEA 다운로드
IntelliJ IDEA를 다운로드합니다.
만든 프로젝트 가져오기
JPA 코멘트 아웃
build.gradle.kts
dependencies {
// implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
compileOnly("org.projectlombok:lombok")
annotationProcessor("org.projectlombok:lombok")
testImplementation("org.springframework.boot:spring-boot-starter-test")
}
컨트롤러 작성
DemoController.kt
package com.example.demo.controller
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/demo")
class DemoController {
@GetMapping("/getAll")
fun getAll(): ResponseEntity<String> {
return ResponseEntity.ok("Demo")
}
}
프로젝트 시작
18:32:18: Executing task 'bootRun'...
> Task :compileKotlin
> Task :compileJava NO-SOURCE
> Task :processResources UP-TO-DATE
> Task :classes UP-TO-DATE
> Task :bootRunMainClassName
> Task :bootRun
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.3)
2021-03-13 18:32:21.905 INFO 8184 --- [ main] com.example.demo.DemoApplicationKt : Starting DemoApplicationKt using Java 1.8.0_241 on DESKTOP-I88K5MF with PID 8184
2021-03-13 18:32:21.905 INFO 8184 --- [ main] com.example.demo.DemoApplicationKt : No active profile set, falling back to default profiles: default
2021-03-13 18:32:23.034 INFO 8184 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-03-13 18:32:23.050 INFO 8184 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-03-13 18:32:23.050 INFO 8184 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.43]
2021-03-13 18:32:23.128 INFO 8184 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-03-13 18:32:23.128 INFO 8184 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1155 ms
2021-03-13 18:32:23.425 INFO 8184 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2021-03-13 18:32:23.662 INFO 8184 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-03-13 18:32:23.677 INFO 8184 --- [ main] com.example.demo.DemoApplicationKt : Started DemoApplicationKt in 2.308 seconds (JVM running for 2.822)
2021-03-13 18:32:26.108 INFO 8184 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-03-13 18:32:26.108 INFO 8184 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-03-13 18:32:26.116 INFO 8184 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 8 ms
JPA로 데이터 액세스를 위해 Mysql 준비
create database demo;
use demo;
create table demo (
id int auto_increment,
name varchar(256),
PRIMARY KEY (id)
);
insert into demo (name) values ("test");
application.properties에 설정 추가
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.database=MYSQL
spring.jpa.hibernate.ddl-auto=update
참고:
Java에서 DB (MySQL) 연결을 시도하면 오류가 발생하는 솔루션
SpringBoot + Spring JPA로 데이터베이스에 연결
JPA를 주석 처리하고 드라이버 추가
build.gradle.kts
dependencies {
+ implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
+ implementation("mysql:mysql-connector-java:8.0.20")
compileOnly("org.projectlombok:lombok")
annotationProcessor("org.projectlombok:lombok")
testImplementation("org.springframework.boot:spring-boot-starter-test")
}
엔티티 만들기
Demo.kt
package com.example.demo.entity
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id
@Entity
class Demo (
var name: String? = null,
@Id
@GeneratedValue
var id: Long? = null)
리포지토리 생성
DemoRepository.kt
package com.example.demo.repository
import com.example.demo.entity.Demo
import org.springframework.data.repository.CrudRepository
interface DemoRepository : CrudRepository<Demo, Long> {
fun findAllByOrderById(): Iterable<Demo>
}
컨트롤러 수정
DemoController.kt
package com.example.demo.controller
import com.example.demo.entity.Demo
import com.example.demo.repository.DemoRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/demo")
class DemoController @Autowired constructor( //修正
val demoRepository: DemoRepository) //修正
{ //修正
@GetMapping("/getAll")
fun getAll(): ResponseEntity<Iterable<Demo>> { //修正
val demos = demoRepository.findAllByOrderById() //修正
return ResponseEntity.ok(demos) //修正
}
}
브라우저에서 표시
요약
참고:
Getting started with Spring Data JPA
Kotlin with Spring Boot 2.0에서 간단한 Rest API 구현
Reference
이 문제에 관하여(Kotlin + SpringBoot로 최소 WebAPI 구축), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/kyabetsuda/items/d48fb744d793ff4faf65텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)