App.kt
fun main(args: Array<String>) {
println("HelloKT")
}
kotlinc App.kt
在当前目录编译生成AppKt.classkotlin AppKt
运行类AppKt(等价于java AppKt
带上Kotlin的依赖库)Gradle配置Kotlin,需要一个插件(Kotlin的Gradle插件kotlin-gradle-plugin) 和一个依赖(Kotlin标准库kotlin-stdlib)
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.50'
}
}
apply plugin: 'application'
apply plugin: 'kotlin'
mainClassName = 'MyApp'
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib"
}
repositories {
jcenter()
}
添加"kotlin"插件后,就不需要"java"插件了
MyApp.kt
/**
* Created by BaiJiFeiLong@gmail.com at 18-6-27 下午10:08
*/
class MyApp {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println("hello kt")
}
}
}
Kotlin文件可以放在src/main/java
中,也可以放在src/main/kotlin
中,默认情况下都能识别
之所以把main方法写到类里面,是因为Gradle的Application插件(gradle run
)需要运行
指定类(mainClassName)的main方法,所以main方法必须放在类中,否则Application插件无法工作
运行程序:gradle run
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.50'
classpath 'org.springframework.boot:spring-boot-gradle-plugin:2.0.3.RELEASE'
}
}
apply plugin: 'application'
apply plugin: 'kotlin'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
mainClassName = 'bj.App'
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib"
compile "org.jetbrains.kotlin:kotlin-reflect" // @Bean @Component needed
compile 'org.springframework.boot:spring-boot-starter'
}
repositories {
jcenter()
}
App.kt
package bj
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.context.ApplicationListener
/**
* Created by BaiJiFeiLong@gmail.com at 18-6-27 下午10:08
*/
@SpringBootApplication
open class App : ApplicationListener<ApplicationReadyEvent> {
override fun onApplicationEvent(event: ApplicationReadyEvent?) {
println("Ready.")
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
SpringApplication.run(App::class.java, *args);
}
}
}
注意:
java.lang.ClassNotFoundException: org.springframework.dao.DataAccessException
kotlin-reflect
,否则在使用注解@Bean和@Component的时候会报异常java.lang.ClassNotFoundException: kotlin.reflect.jvm.ReflectJvmMapping