您好,登錄后才能下訂單哦!
今天我們嘗試Spring Boot整合Kotlin,并決定建立一個非常簡單的Spring Boot微服務,使用Kotlin作為編程語言進行編碼構建。
創建一個簡單的Spring Boot應用程序。我會在這里使用maven構建項目:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.edurt.ski</groupId> <artifactId>springboot-kotlin-integration</artifactId> <version>1.0.0</version> <packaging>jar</packaging> <name>springboot kotlin integration</name> <description>SpringBoot Kotlin Integration is a open source springboot, kotlin integration example.</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <!-- plugin config --> <plugin.maven.kotlin.version>1.2.71</plugin.maven.kotlin.version> </properties> <dependencies> <!-- spring boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- kotlin --> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-kotlin</artifactId> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib-jdk8</artifactId> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-reflect</artifactId> </dependency> </dependencies> <build> <sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory> <testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <artifactId>kotlin-maven-plugin</artifactId> <groupId>org.jetbrains.kotlin</groupId> <configuration> <args> <arg>-Xjsr305=strict</arg> </args> <compilerPlugins> <plugin>spring</plugin> <plugin>jpa</plugin> <plugin>all-open</plugin> </compilerPlugins> <pluginOptions> <option>all-open:annotation=javax.persistence.Entity</option> </pluginOptions> </configuration> <dependencies> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-allopen</artifactId> <version>${plugin.maven.kotlin.version}</version> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-noarg</artifactId> <version>${plugin.maven.kotlin.version}</version> </dependency> </dependencies> <executions> <execution> <id>kapt</id> <goals> <goal>kapt</goal> </goals> <configuration> <sourceDirs> <sourceDir>src/main/kotlin</sourceDir> </sourceDirs> <annotationProcessorPaths> <annotationProcessorPath> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <version>${project.parent.version}</version> </annotationProcessorPath> </annotationProcessorPaths> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
添加所有必需的依賴項:
一個簡單的應用類:
package com.edurt.ski import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class SpringBootKotlinIntegration fun main(args: Array<String>) { runApplication<SpringBootKotlinIntegration>(*args) }
添加Rest API接口功能
創建一個HelloController Rest API接口,我們只提供一個簡單的get請求獲取hello,kotlin輸出信息:
package com.edurt.ski.controller import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController @RestController class HelloController { @GetMapping(value = "hello") fun hello(): String { return "hello,kotlin" } }
修改SpringBootKotlinIntegration文件增加以下設置掃描路徑
@ComponentScan(value = [ "com.edurt.ski", "com.edurt.ski.controller" ])
添加頁面功能
修改pom.xml文件增加以下頁面依賴
<!-- mustache --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mustache</artifactId> </dependency>
在src/main/resources路徑下創建templates文件夾
在templates文件夾下創建一個名為hello.mustache的頁面文件
<h2>Hello, Kotlin</h2>
創建頁面轉換器HelloView
package com.edurt.ski.view import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.web.bind.annotation.GetMapping @Controller class HelloView { @GetMapping(value = "hello_view") fun helloView(model: Model): String { return "hello" } }
瀏覽器訪問http://localhost:8080/hello_view即可看到頁面內容
添加數據持久化功能
修改pom.xml文件增加以下依賴(由于測試功能我們使用h3內存數據庫)
<!-- data jpa and db --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h3database</groupId> <artifactId>h3</artifactId> <scope>runtime</scope> </dependency>
創建User實體
package com.edurt.ski.model import javax.persistence.Entity import javax.persistence.GeneratedValue import javax.persistence.Id @Entity //class UserModel( // @Id // @GeneratedValue // private var id: Long? = 0, // private var name: String //) class UserModel { @Id @GeneratedValue var id: Long? = 0 get() = field set var name: String? = null get() = field set }
創建UserSupport dao數據庫操作工具類
package com.edurt.ski.support import com.edurt.ski.model.UserModel import org.springframework.data.repository.PagingAndSortingRepository interface UserSupport : PagingAndSortingRepository<UserModel, Long> { }
創建UserService服務類
package com.edurt.ski.service import com.edurt.ski.model.UserModel interface UserService { /** * save model to db */ fun save(model: UserModel): UserModel }
創建UserServiceImpl實現類
package com.edurt.ski.service import com.edurt.ski.model.UserModel import com.edurt.ski.support.UserSupport import org.springframework.stereotype.Service @Service(value = "userService") class UserServiceImpl(private val userSupport: UserSupport) : UserService { override fun save(model: UserModel): UserModel { return this.userSupport.save(model) } }
創建用戶UserController進行持久化數據
package com.edurt.ski.controller import com.edurt.ski.model.UserModel import com.edurt.ski.service.UserService import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping(value = "user") class UserController(private val userService: UserService) { @PostMapping(value = "save/{name}") fun save(@PathVariable name: String): UserModel { val userModel = UserModel() // userModel.id = 1 userModel.name = name return this.userService.save(userModel) } }
使用控制臺窗口執行以下命令保存數據
curl -X POST http://localhost:8080/user/save/qianmoQ
收到返回結果
{"id":1,"name":"qianmoQ"}
表示數據保存成功
增加數據讀取渲染功能
修改UserService增加以下代碼
/** * get all model */ fun getAll(page: Pageable): Page<UserModel>
修改UserServiceImpl增加以下代碼
override fun getAll(page: Pageable): Page<UserModel> { return this.userSupport.findAll(page) }
修改UserController增加以下代碼
@GetMapping(value = "list") fun get(): Page<UserModel> = this.userService.getAll(PageRequest(0, 10))
創建UserView文件渲染User數據
package com.edurt.ski.view import com.edurt.ski.service.UserService import org.springframework.data.domain.PageRequest import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.ui.set import org.springframework.web.bind.annotation.GetMapping @Controller class UserView(private val userService: UserService) { @GetMapping(value = "user_view") fun helloView(model: Model): String { model["users"] = this.userService.getAll(PageRequest(0, 10)) return "user" } }
創建user.mustache文件渲染數據(自行解析返回數據即可)
{{users}}
瀏覽器訪問http://localhost:8080/user_view即可看到頁面內容
增加單元功能
修改pom.xml文件增加以下依賴
<!-- test --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>junit</groupId> <artifactId>junit</artifactId> </exclusion> <exclusion> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <scope>test</scope> </dependency>
創建UserServiceTest文件進行測試UserService功能
package com.edurt.ski import com.edurt.ski.service.UserService import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.data.domain.PageRequest @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class UserServiceTest(@Autowired private val userService: UserService) { @Test fun `get all`() { println(">> Assert blog page title, content and status code") val entity = this.userService.getAll(PageRequest(0, 1)) print(entity.totalPages) } }
源碼地址:GitHub
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。