안드로이드 개발자이지만, 간단하게 SpringBoot 프로젝트를 만드는 방법을 포스트해보고자 합니다.
프로젝트 생성
저같은 경우는 아직 학생신분이라서 Student License를 이용하여 Intellij Ultimate버전을 사용하므로 Intellij로 프로젝트를 생성할 수 있지만 Community버전을 이용하는 경우 https://start.spring.io 사이트를 통해 프로젝트를 생성하셔야합니다.
저같은 경우는 SpringBoot + Spring Data JPA + Kotlin + MySQL 조합을 사용하므로 저렇게 4개의 의존성을 추가해주었습니다. 또한 코틀린을 사용하므로 primary 생성자와 data class가 Lombok이 해주는 일을 모두 해주므로 의존성을 추가하지 않습니다.
프로젝트 설정
gradle 설정
build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "2.3.4.RELEASE"
id("io.spring.dependency-management") version "1.0.10.RELEASE"
kotlin("jvm") version "1.3.72"
kotlin("plugin.spring") version "1.3.72"
kotlin("plugin.jpa") version "1.3.72"
}
group = "io.github.slflfl12"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11
configurations {
compileOnly {
extendsFrom(configurations.annotationProcessor.get())
}
}
repositories {
mavenCentral()
}
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("mysql:mysql-connector-java") // 커넥터 추가
implementation("org.springframework.boot:spring-boot-starter-jdbc")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
developmentOnly("org.springframework.boot:spring-boot-devtools")
testImplementation("org.springframework.boot:spring-boot-starter-test") {
exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
}
testImplementation("org.springframework.security:spring-security-test")
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "11"
}
}
application.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/spring_boot_template?serverTimezone=UTC&characterEncoding=UTF-8
username: root
password: 1234
jpa:
hibernate:
ddl-auto: update
generate-ddl: true
show-sql: true
MySQL과 연동하려면 Connector-Java를 추가하셔야 하고
application.yml같은 경우는 간단하게 제작할 예정이므로 많은 설정은 하지 않았습니다.
MySQL 연결
오른쪽의 Database 탭을 눌러서 자기가 사용하는 데이터베이스를 연결해줍니다.
그 뒤 아이디, 비밀번호를 입력하고 URL에 serverTimezone을 뒤에 추가한 다음 Test Connection을 통해 연결이 되었는지 확인합니다.
연결이 되었으면 정상적으로 데이터베이스와 스키마가 보이는 것을 알 수 있습니다.
프로젝트 구조
패키징은 자신이 사용하시는 만큼 아키텍처에 맞게 넣어 주시면 됩니다.
코드 작성
Controller -> Service -> Repository -> (DB) 순대로 나열하겠습니다.
TemplateController.kt
package io.github.slflfl12.springboottemplate.controller
import io.github.slflfl12.springboottemplate.model.TemplateModel
import io.github.slflfl12.springboottemplate.service.TemplateService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
@RestController // @Controller + @ResponseBody
@RequestMapping//("/template")
class TemplateController {
@Autowired
private lateinit var templateService: TemplateService
@GetMapping("/templates")
private fun getTemplates(): ResponseEntity<Any> {
return ResponseEntity
.ok()
.body(templateService.getAllTemplates())
}
@GetMapping("/template/{id}")
private fun getTemplateById(@PathVariable id: Int): ResponseEntity<Any> {
return ResponseEntity
.ok()
.body(templateService.getTemplate(id))
}
@GetMapping("/template")
private fun getTemplateByName(@RequestParam(value = "name") name: String): ResponseEntity<Any?> {
return ResponseEntity
.ok()
.body(templateService.getTemplateByName(name))
}
@PostMapping("/template")
private fun postTemplate(@RequestBody templateModel: TemplateModel): ResponseEntity<Any> {
templateService.saveTemplate(templateModel)
return ResponseEntity
.ok()
.body(true)
}
}
TemplateService.kt
package io.github.slflfl12.springboottemplate.service
import io.github.slflfl12.springboottemplate.model.TemplateModel
import org.springframework.stereotype.Service
@Service
interface TemplateService {
fun getAllTemplates(): List<TemplateModel>?
fun getTemplate(id: Int): TemplateModel?
fun saveTemplate(templateModel: TemplateModel): TemplateModel
fun getTemplateByName(name: String): TemplateModel?
}
TemplateServiceImpl.kt
package io.github.slflfl12.springboottemplate.service
import io.github.slflfl12.springboottemplate.model.TemplateModel
import io.github.slflfl12.springboottemplate.repository.TemplateRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import javax.transaction.Transactional
@Service
class TemplateServiceImpl constructor(@Autowired private val templateRepository: TemplateRepository) : TemplateService {
override fun getAllTemplates(): List<TemplateModel>? =
templateRepository.findAllBy()
override fun getTemplate(id: Int): TemplateModel? =
templateRepository.findById(id).orElse(null)
override fun getTemplateByName(name: String): TemplateModel? {
return templateRepository.findByTemplateName(name)
}
@Transactional
override fun saveTemplate(templateModel: TemplateModel): TemplateModel =
templateRepository.save(templateModel)
}
TemplateRepository.kt
package io.github.slflfl12.springboottemplate.repository
import io.github.slflfl12.springboottemplate.model.TemplateModel
import org.springframework.data.repository.CrudRepository
interface TemplateRepository: CrudRepository<TemplateModel,Int> {
fun findByTemplateName(templateName: String): TemplateModel?
fun findAllBy(): List<TemplateModel>?
}
TemplateModel.kt
package io.github.slflfl12.springboottemplate.model
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id
@Entity
data class TemplateModel(
@Id
@GeneratedValue
val id: Int,
val templateName: String,
val content: String)
실행 결과
간단한 팁
CrudRepository를 이용하면 Optional 타입을 리턴하는 findById()가 override 되어있을 것 입니다. 코틀린을 이용하시는 여러분들은 null처리가 가능한 nullable타입을 리턴하고 싶으실텐데 말이죠.
코틀린 유저들을 위해 만든 리턴타입 orElse() 메소드를 사용하시면 바로 nullable 객체를 리턴하실 수 있습니다.
후기
Java Spring을 다루던 지식과 블로그 포스트 몇개를 보고 작성한 포스트입니다. 안드로이드 개발자인지라 서버지식이 부족한 부분이 있을 수도 있어 잘못 사용된 부분이 있을 수도 있는데 혹시라도 틀린 부분이 있거나 개선해야 할 점이 보이신다면 댓글 남겨주시면 감사하겠습니다.
코드 : https://github.com/slflfl12/spring-boot-kotlin-template