Spring Boot+Kotlin

当遇到kotlin后,可能再也不想写Java代码了。kotlin 相对scala来说入门更简单。

要用到的开发工具有:

先来创建一个打印用户名列表的程序练练手。

打开IDEA, 选择Gradle, 再选择kotlin, 然后按照提示完成工程的创建。

创建完毕后,默认是没有源代码目录,需要在根目录下创建src/main/kotlin,src/main/resources, 以及单元测试需要的src/test/kotlin, src/test/resources目录。

修改build.gradle,

group 'com.foo'
version '0.1'

buildscript {
    ext.kotlin_version = '1.3.41'

    repositories {
        mavenLocal()
        maven {
            url "https://maven.aliyun.com/nexus/content/groups/public"
        }
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

apply plugin: 'kotlin'
apply plugin: 'application'
mainClassName="com.foo.bar.StartKt"

repositories {
    mavenLocal()
    maven {
            url "https://maven.aliyun.com/nexus/content/groups/public"
    }
    mavenCentral()
}

compileKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    implementation "org.springframework.boot:spring-boot-starter-jdbc:2.1.7.RELEASE"
    testImplementation group: 'junit', name:'junit', version: '4.12'
    runtimeOnly group: 'mysql', name: 'mysql-connector-java', version: '5.1.36'
}

假设启动文件是com.foo.bar下面的Start.kt 文件, 对应的java类名为com.foo.bar.StartKt

选择src/main/kotlin, 创建包com.foo.bar,新建kotlin文件Start.kt, 代码为

package com.foo.bar

import org.springframework.boot.SpringApplication

fun main(args:Array<String>){
    SpringApplication.run(AppConfig::class.java)
}

接着在同一个包下创建AppConfig的kotlin类

package com.foo.bar

import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration


@Configuration
@EnableAutoConfiguration
@ComponentScan("com.foo.bar.dao")
open class AppConfig {

    @Bean
    open fun runner(): ReportCommander {
        return ReportCommander()
    }


}

准备spring boot所需的application.properties, 在src/main/resources目录下

spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

创建Model

package com.foo.bar

data class User(val userId: Int, val name: String)

在com.foo.bar下新建dao包, 创建Dao类:

package com.foo.bar.dao

import com.foo.bar.User
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.stereotype.Component

@Component
class UserRepository {

    @Autowired
    private lateinit var jt:NamedParameterJdbcTemplate

    fun queryUsers(maxId: Int):List<User>{
        val params= mapOf("maxId" to maxId)
        return jt.query("""select userId, userName
        |From test.user
        |where userId<:maxId""".trimMargin(), params){rs, _->
            User(userId=rs.getInt(1),
			       name=rs.getString(2))
        }
    }

}

最后创建Runner

package com.foo.bar

import com.foo.bar.dao.UserRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.CommandLineRunner
import org.springframework.transaction.support.TransactionTemplate

class ReportCommander : CommandLineRunner {

    @Autowired
    private lateinit var userRepositoy: UserRepository

    @Autowired
    private lateinit var tx: TransactionTemplate

    override fun run(vararg p0: String?) {

        tx.execute {
            userRepositoy.queryUsers(100).forEach { user->
                println("name=${user.name}")
            }
        }

    }
}

最后定位到Start.kt文件, 你会发现在fun main  这一行的左边有一个K形状的图标,点击它就可以直接运行了。

当然也可以使用gradle run来运行。

当你看到这个输出的时候,就成功了!

下午10:31:58: Executing external task 'run'...
:compileKotlin
:compileJava UP-TO-DATE
:copyMainKotlinClasses
:processResources
:classes
:run

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.1.RELEASE)

2016-11-16 22:32:19.486  INFO 4786 --- [           main] com.foo.bar.StartKt                      : Starting StartKt on bogon with PID 4786 (/Users/xxx/projects/bar/build/classes/main started by xxx in /Users/xxx/projects/bar)
2016-11-16 22:32:19.490  INFO 4786 --- [           main] com.foo.bar.StartKt                      : No active profile set, falling back to default profiles: default
2016-11-16 22:32:19.595  INFO 4786 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@581118e6: startup date [Wed Nov 16 22:32:19 CST 2016]; root of context hierarchy
2016-11-16 22:32:22.128  INFO 4786 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup

name=aaa
name=bbbbb
name=cccccc
name=dddddd

2016-11-16 22:32:22.784  INFO 4786 --- [           main] com.foo.bar.StartKt                      : Started StartKt in 6.139 seconds (JVM running for 6.625)
2016-11-16 22:32:22.791  INFO 4786 --- [       Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@581118e6: startup date [Wed Nov 16 22:32:19 CST 2016]; root of context hierarchy
2016-11-16 22:32:22.796  INFO 4786 --- [       Thread-1] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

BUILD SUCCESSFUL

Total time: 23.83 secs
下午10:32:23: External task execution finished 'run'.

转载于:https://my.oschina.net/u/2009085/blog/789378

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值