配置
要想实现Springboot使用Kotlin和Java混合编程,需要使用kotlin插件:
spring-boot-gradle-plugin
kotlin-gradle-plugin
具体配置如下:
apply {
plugin "kotlin"
plugin "kotlin-spring"
plugin "kotlin-jpa"
plugin "org.springframework.boot"
plugin 'java'
plugin 'eclipse'
plugin 'idea'
plugin 'war'
plugin 'maven'
}
sourceSets {
main {
kotlin { srcDir "src/main/kotlin" }
java { srcDir "src/main/java" }
}
test {
kotlin { srcDir "src/test/kotlin" }
java { srcDir "src/test/java" }
}
}
buildscript {
ext {
kotlinVersion = '1.1.0'
springBootVersion = '1.5.2.RELEASE'
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlinVersion"
classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlinVersion"
}
}
dependencies {
compile("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion")
compile("org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion")
compile("com.fasterxml.jackson.module:jackson-module-kotlin:2.8.4")
...
}
完整的配置参考:
https://github.com/Jason-Chen-2017/restfeel/blob/master/build.gradle
工程目录结构
工程目录完整的工程目录,可以参考:
https://github.com/Jason-Chen-2017/restfeel
把工程git clone下来,命令行tree一下,即可看到。
让kotlin代码的归kotlin目录,java代码归java目录
比如说,我们把SpringBoot启动类放到kotlin下面:
package com.restfeel
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.SpringApplication
import org.springframework.core.env.Environment
/**
* Created by jack on 2017/3/29.
* @author jack
* @date 2017/03/29
*/
@RestFeelBoot
class RestFeelApplicationKotlin : CommandLineRunner {
@Autowired
private val env: Environment? = null
override fun run(vararg args: String?) {
println("RESTFEEL 启动完毕")
println("应用地址:" + env?.getProperty("application.host-uri"))
}
}
fun main(args: Array<String>) {
SpringApplication.run(RestFeelApplicationKotlin::class.java, *args)
}
执行
gradle bootRun
系统会正常运行的。
Java代码Kotlin代码互相调用
我们放到后面单独的一章来讲。
网友评论