使用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 cloud 版本
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<String>) {
	runApplication<ProductApplication>(*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<SpuPO,Long>

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

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiegwei

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值