Spring Boot 2 + Kotlin DSL + Flux Web

SpringbootdemoApplication.kt

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package io.igordonxiao.springbootdemo

import org.springframework.boot.Banner.Mode.OFF
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.server.ServerResponse.ok
import org.springframework.web.reactive.function.server.router
import org.springframework.web.server.ServerWebExchange
import org.springframework.web.server.WebFilter
import org.springframework.web.server.WebFilterChain
import reactor.core.publisher.Mono
import reactor.core.publisher.toMono


@SpringBootApplication
class SpringbootdemoApplication

@Document
data class User(@Id val id: String, val name: String)

interface IUserRepository : ReactiveMongoRepository<User, String>

@Configuration
class ApiRoutes(private val userRepository: IUserRepository) {

    @Bean
    fun apiRouter() = router {

        "/users".nest {
            GET("/") {
                ok().body(userRepository.findAll(), User::class.java)
            }
            POST("/") {
                ok().body(userRepository.insert(it.bodyToMono(User::class.java)).toMono(), User::class.java)
            }
        }

    }
}

fun main(args: Array<String>) {
    runApplication<SpringbootdemoApplication>(*args) {
        setBannerMode(OFF)
    }
}

Kotlin的扩展及DSL让代码显示非常简洁,少了很多模板代码。

完整示例