使用kotlin编写spring cloud微服务的过程

网友投稿 805 2022-12-12

使用kotlin编写spring cloud微服务的过程

使用kotlin编写spring cloud微服务的过程

创建工程

使用idea的spring initializr创建一个项目,语言选择kotlin, 类型为gradle。

根据需要选择依赖

配置文件

yml或者properties文件和java是完全一样的,这里不详细说明

修改build.gradle.kts中的参数

plugins {

//spring boot版本

id("org.springframework.boot") version "2.3.3.RELEASE"

//自动依赖包版本管理

id("io.spring.dependency-management") version "1.0.10.RELEASE"

...

}

//spring chttp://loud 版本

extra["springCloudVersion"] = "Hoxton.SR8"

repositories {

//本地maven

maven {

url = uri("http://192.168.1.150:8081/repository/maven-public/")

credentials {

username = "admin"

password = "admin"

}

}

maven { url = uri("https://repo.spring.io/milestone") }

jcenter {

content {

// just allow to include kotlinx projects

// detekt needs 'kotlinx-html' for the html report

includeGroup("org.jetbrains.kotlinx")

}

}

}

...

Application

/**

* 商品服务

*/

@SpringBootApplication

class ProductApplication

/**

* 程序入口

*/

fun main(args: Array) {

runApplication(*args)

}

这是自动生成程序入口,不用修改

编写controller

@RestController

@RequestMapping("v2/test")

class SpuManagerController(val xService: XService) {

@PostMapping("")

fun addSpu(@RequestBody addXxVO: AddXxVO):Long{

return xrService.addX(addXxVO)

}

}

这是一个controller,通过构造函数注入依赖。

JPA

实体类:

@Entity(name = "table_name")

@DynamicInsert //不插入null

@DynamicUpdate

class XxPO(

var code:String,

var name:String,

var createDate:Date?=null,

var updatedDate: Date?=null,

@Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id:Long?=null)

Repository:

interface XxRepository :CrudRepository

由于没有自定义的方法,直接定义一个接口即可。

Service

单元测试

@SpringBootTest

@AutoConfigureMockMvc

@Transactional

class SpuManagerControllerTests @Autowired constructor(val mockMvc: MockMvc,

val xxRepository : XxRepository ) {

@Test

fun testAddSpu() {

val vo= AddXxVO("test_code", "test_name")

mockMvc.perform(

MockMvcRequestBuilders.post("/v2/test")

.contentType(MediaType.APPLICATION_jsON)

.content(JSON.toJSONString(vo))

).andExpect {

status().is2xxSuccessful

}

.andReturn()

.response

.contentAsString

.apply {

val id = this.toLong()

val result = xxRepository .findById(id)

assert(result.isPresent)

}

}

}

注意 @Test对应的类是 org.junit.jupiter.api.Test

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:解决Test类中不能使用Autowired注入bean的问题
下一篇:Hadoop源码分析五hdfs架构原理剖析
相关文章

 发表评论

暂时没有评论,来抢沙发吧~