美文网首页Kotlin精选Kotlin专题Kotlin
使用Kotlin开发spring boot应用

使用Kotlin开发spring boot应用

作者: blurooo | 来源:发表于2017-06-14 13:11 被阅读1652次

1. Kotlin的优势

  • Kotlin是一种静态类型的语言,但由于其巧妙的类型推断,它允许你编写的代码与动态语言一样简短而富有表现力,表现接近于纯Java项目
  • 属性(properties)支持
  • 与其他语言相比拥有相对轻巧的标准库
  • 易于学习:Java开发人员可以快速了解大部分语言
  • 可与Java互操作
  • 适合Android开发(已成为谷歌安卓官方指定开发语言)
  • 内置的不可变性和空指针安全的支持
  • 代码易于阅读,高效编写
  • 允许扩展现有库,而不必继承类或使用任何类型的设计模式,如Decorator
  • 句尾不需要分号;

Kotlin disget 2015 的博客里可以找到大量有用的信息帮助你认识Kotlin,也可以在 kotlin在线 练习Kotlin语言。

2. 初窥 Spring Boot + Kotlin 项目

Kotlin允许使用非常简短的定义方式(data class)声明实体类,参数允许指定默认值,参数类型在参数之后给出:

@Entity
data class Customer(
    var firstName: String = "",
    var lastName: String = "",
    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    var id: Long = 0
)

请注意跟在data class之后的是一个圆括号,而不是常见类的花括号。

@RestController
class CustomerController (val repository:CustomerRepository) {

    @GetMapping("/")
    fun findAll() = repository.findAll()

    @GetMapping("/{name}")
    fun findByLastName(@PathVariable name:String)
        = repository.findByLastName(name)
}
  1. 上面可以看到一个 Spring MVC REST controller 采用了构造函数级别的注入方式,而且 Kotlin 默认类可见性为public(java为default),所以不必特别指定。
  2. 如果函数返回一个单句表达式,允许不写花括号,直接让函数 = 该表达式,那么返回类型将由Kotlin自动推断。
interface CustomerRepository : CrudRepository<Customer, Long> {
    fun findByLastName(name: String): List<Customer>
}

定义一个 Spring Data repository 也非常简单。

@SpringBootApplication
open class Application {

    @Bean
    open fun init(repository: CustomerRepository) = CommandLineRunner {
        repository.save(Customer("Jack", "Bauer"))
        repository.save(Customer("Chloe", "O'Brian"))
        repository.save(Customer("Kim", "Bauer"))
        repository.save(Customer("David", "Palmer"))
        repository.save(Customer("Michelle", "Dessler"))
    }
}

fun main(args: Array<String>) {
    SpringApplication.run(Application::class.java, *args)
}
  1. 在Java中,函数必须寄身于类,而Kotlin可以支持顶级函数。所以可以像上面的方式声明我们的 Spring Boot 入口类。
  2. 在Kotlin中类和方法都默认为final,不允许被继承/覆写。如果需要,请添加open修饰符。

3. 额外说明

  1. 数组注解属性无法像Java一样

    // java
    @RequestMapping(method = RequestMethod.GET)
    
    // kotlin
    @RequestMapping(method = arrayOf(RequestMethod.GET))
    

    不过kotlin1.1有对它进行了改善,可以查看这个issue

  2. 属性注入问题

    var name = "cmx";
    var hello = "My name is ${name}";
    @Value("\${some.property}")
    

    在kotlin中,$ 被用于字符串插值,所以 @Value 属性注入时,其中 $ 前应当添加 反斜线 进行转义或采用 @ConfigurationProperties 替代。

  3. 使用Jackson的问题

    如果你使用的是Jackson,你可能需要添加 com.fasterxml.jackson.module:jackson-module-kotlin 的依赖关系,以允许它处理没有默认构造函数或Kotlin集合的数据类。在 Spring Framework 4.3+ 中已经自动注册。

4. demo起步

IntelliJ IDEA 目前可以直接创建采用Kotlin语言的spring boot项目,选择language为kotlin即可。

附github:mongo + kotlin小案例

相关文章

网友评论

    本文标题:使用Kotlin开发spring boot应用

    本文链接:https://www.haomeiwen.com/subject/bfvsqxtx.html