本篇主要介绍一下 kotlin + springboot的服务端开发环境搭建

Kotlin 是一个基于JVM的编程语言, 是IDEA开发工具 jetbrains 公司开发的语言,也被google选为android开发的首选语言, 因为它是完全兼容Java的 所以也可以做后端开发 比如集成我们在使用Java的一些技术框架 ,本篇就来简单介绍一下和SpringBoot的集成
下面我用Gradle init 的方式从头开始搭建Kotlin 集成SpringBoot环境, 你也可以通过IDEA直接创建 SpringBoot项目里面选择Kotlin语言即可, 我这里不展示了
可以通过gradle init 命令初始化项目 按照提示 选择 kotlin语言 , kotlin dsl 等等..

需要配置几个插件 包括 springboot gradle 插件
org.springframework.boot
Spring Boot 官方提供了Gradle插件支持,可以打包程序为可执行的 jar 或 war 包,运行 Spring Boot 应用程序,并且使用spring-boot-dependencies 管理版本
io.spring.dependency-management
自动从你正在使用的springbooot版本中导入spring-boot-dependencies bom
kotlin("jvm") : 指定kotlin的版本
kotlin("plugin.spring") : 用于在给类添加 open 关键字(否则是final的) 仅限于spring的一些注解比如@Controller
@Service ..
kotlin("plugin.jpa") : 用于生成kotlin 数据类 无参构造函数,否则会提示Entity缺少缺省构造函数
plugins {
// Apply the org.jetbrains.kotlin.jvm Plugin to add support for Kotlin.
// id("org.jetbrains.kotlin.jvm") version "1.7.10"
id("org.springframework.boot") version "2.6.11"
id("io.spring.dependency-management") version "1.0.13.RELEASE"
kotlin("jvm") version "1.6.21"
//引入spring插件 可以给 一些spring注解的类 添加 open关键字 解决kotlin 默认final问题
kotlin("plugin.spring") version "1.6.21"
//引入jpa插件 主要可以给JPA的一些注解类添加 无参构造函数
kotlin("plugin.jpa") version "1.6.21"
// Apply the application plugin to add support for building a CLI application in Java.
}
java.sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom(configurations.annotationProcessor.get())
}
}
dependencies {
// Use the Kotlin JUnit 5 integration.
testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
// Use the JUnit 5 integration.
testImplementation("org.junit.jupiter:junit-jupiter-engine:5.9.1")
// This dependency is used by the application.
implementation("com.google.guava:guava:31.1-jre")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
//引入springboot web依赖
implementation("org.springframework.boot:spring-boot-starter-web")
}
tasks.named<Test>("test") {
// Use JUnit Platform for unit tests.
useJUnitPlatform()
}
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "1.8"
}
}
直接手动创建一个即可, 内容和 原生Java 差不多 因为添加了 plugin.spring所以不需要添加open关键字了
package kotlinspringbootdemo
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class KotlinSpringBootApplication
fun main(args: Array<String>) {
runApplication<KotlinSpringBootApplication>(*args)
}
可以看到controller 和 Java 写法 基本差不多 是不是很像
@RestController
class HelloController {
data class KotlinInfo(val name: String, val desc: String)
@GetMapping("/getKotlin")
fun getKotlinSpringBoot(): KotlinInfo {
return KotlinInfo("kotlin", "kotlin springboot")
}
}
在resources 下面创建一个 application.yaml文件即可
server:
port: 8899
可以看到成功返回了数据

下面来看看如何集成JPA
这个插件的作用是给 @Entity 等JPA的实体 添加 无参构造方法的, 下面是spring官网对这个插件的解释
In order to be able to use Kotlin non-nullable properties with JPA, Kotlin JPA plugin is also enabled. It generates no-arg constructors for any class annotated with @Entity, @MappedSuperclass or @Embeddable.
//引入jpa插件
kotlin("plugin.jpa") version "1.6.21"
jpa的版本由 dependency-management 插件管理
//引入JPA
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
//引入 Mysql
implementation("mysql:mysql-connector-java:8.0.30")
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/kotlinweb?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: root123456
注意哈是 () 构造方法定义的这些属性 , 这是kotlin的构造函数的写法
package kotlinspringbootdemo.entity
import javax.persistence.*
/**
* Created on 2022/12/17 21:28.
* @author Johnny
*/
@Entity
@Table(name = "student")
class StudentInfo(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0,
@Column(name = "name")
val name: String,
@Column(name = "email")
val email: String,
@Column(name = "address")
val address: String
)
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` bigint NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
SET FOREIGN_KEY_CHECKS = 1;
jpa需要定义 repository 这是jpa的知识范围 不多介绍
/**
* @author Johnny
*/
@Repository
interface StudentRepository : JpaRepository<StudentInfo,Long> {
}
除了lateinit 标注 注入的 属性 延迟初始化, 其他的和Java 里面用没啥区别
@RestController
class HelloController {
//注意是 lateinit 延迟初始化
@Autowired
lateinit var studentRepository: StudentRepository
@GetMapping("/add")
fun addStudent(): StudentInfo {
val studentInfo = StudentInfo(name = "johnny", email = "626242589@qq.com", address = "江苏无锡")
studentRepository.save(studentInfo)
return studentInfo
}
}

本篇主要介绍 kotlin springboot 和 jpa的环境搭建和基本使用, 可以看到 基本和java的那套没啥区别
主要是插件那块要弄清楚 这些插件 kotlin spring jpa boot dependency-manager 等等都是干嘛的
//用法一: 这个插件 用于在给类添加 open 关键字(否则是final的) 仅限于spring的一些注解比如@Controller @Service ..等等.
kotlin("plugin.spring") version "1.6.21"
//用法二
id("org.jetbrains.kotlin.plugin.allopen") version "1.6.21"
allOpen{
//把需要open 注解标注的类添加上来
annotation("org.springframework.boot.autoconfigure.SpringBootApplication")
annotation("org.springframework.web.bind.annotation.RestController")
}
//用法三
id("org.jetbrains.kotlin.plugin.allopen") version "1.6.21"
apply{
plugin("kotlin-spring")
}
//详细可以看 : https://kotlinlang.org/docs/all-open-plugin.html#spring-support
欢迎大家访问 个人博客 Johnny小屋
欢迎关注个人公众号

我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当
最近,当我启动我的Rails服务器时,我收到了一长串警告。虽然它不影响我的应用程序,但我想知道如何解决这些警告。我的估计是imagemagick以某种方式被调用了两次?当我在警告前后检查我的git日志时。我想知道如何解决这个问题。-bcrypt-ruby(3.1.2)-better_errors(1.0.1)+bcrypt(3.1.7)+bcrypt-ruby(3.1.5)-bcrypt(>=3.1.3)+better_errors(1.1.0)bcrypt和imagemagick有关系吗?/Users/rbchris/.rbenv/versions/2.0.0-p247/lib/ru
在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo
我已经在Sinatra上创建了应用程序,它代表了一个简单的API。我想在生产和开发上进行部署。我想在部署时选择,是开发还是生产,一些方法的逻辑应该改变,这取决于部署类型。是否有任何想法,如何完成以及解决此问题的一些示例。例子:我有代码get'/api/test'doreturn"Itisdev"end但是在部署到生产环境之后我想在运行/api/test之后看到ItisPROD如何实现? 最佳答案 根据SinatraDocumentation:EnvironmentscanbesetthroughtheRACK_ENVenvironm
我们的git存储库中目前有一个Gemfile。但是,有一个gem我只在我的环境中本地使用(我的团队不使用它)。为了使用它,我必须将它添加到我们的Gemfile中,但每次我checkout到我们的master/dev主分支时,由于与跟踪的gemfile冲突,我必须删除它。我想要的是类似Gemfile.local的东西,它将继承从Gemfile导入的gems,但也允许在那里导入新的gems以供使用只有我的机器。此文件将在.gitignore中被忽略。这可能吗? 最佳答案 设置BUNDLE_GEMFILE环境变量:BUNDLE_GEMFI
这似乎非常适得其反,因为太多的gem会在window上破裂。我一直在处理很多mysql和ruby-mysqlgem问题(gem本身发生段错误,一个名为UnixSocket的类显然在Windows机器上不能正常工作,等等)。我只是在浪费时间吗?我应该转向不同的脚本语言吗? 最佳答案 我在Windows上使用Ruby的经验很少,但是当我开始使用Ruby时,我是在Windows上,我的总体印象是它不是Windows原生系统。因此,在主要使用Windows多年之后,开始使用Ruby促使我切换回原来的系统Unix,这次是Linux。Rub
我想在Ruby中创建一个用于开发目的的极其简单的Web服务器(不,不想使用现成的解决方案)。代码如下:#!/usr/bin/rubyrequire'socket'server=TCPServer.new('127.0.0.1',8080)whileconnection=server.acceptheaders=[]length=0whileline=connection.getsheaders想法是从命令行运行这个脚本,提供另一个脚本,它将在其标准输入上获取请求,并在其标准输出上返回完整的响应。到目前为止一切顺利,但事实证明这真的很脆弱,因为它在第二个请求上中断并出现错误:/usr/b
我正在玩HTML5视频并且在ERB中有以下片段:mp4视频从在我的开发环境中运行的服务器很好地流式传输到chrome。然而firefox显示带有海报图像的视频播放器,但带有一个大X。问题似乎是mongrel不确定ogv扩展的mime类型,并且只返回text/plain,如curl所示:$curl-Ihttp://0.0.0.0:3000/pr6.ogvHTTP/1.1200OKConnection:closeDate:Mon,19Apr201012:33:50GMTLast-Modified:Sun,18Apr201012:46:07GMTContent-Type:text/plain