创建工程

使用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

到此这篇关于使用kotlin编写spring cloud微服务的文章就介绍到这了,更多相关kotlin spring cloud微服务内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!