Transcription
Kotlin 1.4 Online EventThe State of KotlinSupport in SpringSébastien Deleuze@sdeleuzeOctober 15, 2020
Spring is the server-side leader on the JVMSource: a Picture of Java in 2020, JetBrains
First class support for Java and Kotlin
More Spring Boot projectsgenerated with Kotlin each year.
Let’s focus on Kotlin today
Getting started
Start your project on https://start.spring.io
Minimal Spring Boot Kotlin application
Gradle Kotlin DSL
Also available in IDEsIntelliJ IDEA UltimateVS code
Follow the tutorial on https://spring.io/guides
Spring Framework documentation in Kotlin
Choose your style
Choose your web server stackSpring MVCTomcatPersistenceJPAJDBCRedisMongo.NoDo I needasynchronousor reactiveprogramming?YesSpring WebFluxwith CoroutinesNettySpring DataPersistenceSpring DataReactivewith CoroutinesR2DBCRedisMongo.
Choose your programming model
Do you prefer rticle")class ArticleController(private val repository: ArticleRepository) {@GetMapping("/")fun findAll() g("/{slug}")fun findOne(@PathVariable slug: String) repository.findBySlug(slug) ?:throw ResponseStatusException(NOT FOUND)}
Or functional APIs?@Beanfun route(repository: ArticleRepository) router {"/api/article".nest {GET("/") ))}GET("/{slug}") {val slug it.pathVariable("slug")val article repository.findBySlug(slug) ?:throw ResponseStatusException(NOT FOUND)ok().body(article)}}}
Spring supports both,so up to you.
Coroutines
Allow to go reactive with agreat trade-off betweenimperative and functionalprogramming.
Coroutines are the default way togo reactive in Spring with Kotlin.
First class Coroutines support Spring WebFluxSpring MVC (new in Spring Boot 2.4 Spring Data ReactiveSpring Messaging (RSocket)Spring Vault
Suspending functionsSpring MVC and WebFlux@GetMapping("/api/banner")suspend fun suspendingEndpoint(): Banner {delay(10)return Banner("title", "Lorem ipsum")}
FlowSpring MVC and WebFlux@GetMapping("/banners")suspend fun flow(): Flow Banner T EVENT STREAM).retrieve().bodyToFlow String ().map { Banner("title", it) }
Multiplatform
Multiplatform
kotlinx.serialization
kotlinx.serialization supportNew in Spring Boot 2.4 More lightweight than JacksonDesigned for KotlinMultiplatform serializationAllows same code for model and validationacross server, frontend and ring-boot-starter-web") {exclude(module tbrains.kotlinx:kotlinx-serialization-json:1.0.0")
Kotlin/JS
Kotlin/WASM has a huge potential
RSocket
veStreams
.PythonRSocket.NETGoC ReactiveStreamsJavaScriptKotlinJavaRSocketReactor
RSocket support in Spring messagingclass MessageHandler(private val builder: RSocketRequester.Builder) {// .}suspend fun stream(request: ServerRequest): ServerResponse {val requester builder.dataMimeType(APPLICATION CBOR).connectTcpAndAwait("localhost", 9898)val replies ssor).retrieveFlow Message ()val broadcast requester.route("bot.broadcast").retrieveFlow Message ()val messages flowOf(replies, processor.asFlow(), broadcast).flattenMerge()return ok().sse().bodyAndAwait(messages)}
rsocket-kotlin
Other key points
100% of Spring Framework APIwith null-safety annotations no NPE for Spring applicationswritten in Kotlin
ConfigurationProperties data ("blog")data class BlogProperties(val title: String, val banner: Banner) {data class Banner(val title: String? null, val content: String)}
Spring Security Kotlin DSLNew in Spring Security 5.4override fun configure(http: HttpSecurity) {http {authorizeRequests {authorize("/css/**", permitAll)authorize("/user/**", hasAuthority("ROLE USER"))}formLogin {loginPage "/log-in"}}}
Spring Boot native applicationsWith GraalVM native
EXESpring rimage
JVM and native executables offer differenttrade-offs
Instant startup and cheaper hostingSpring Boot on JVM,4 vCPU, 1G RAMSpring Boot on Native,1 vCPU, 256M RAM
Spring support for native executablesIncubating support inspring-graalvm-native plugin(Spring Boot 2 baseline)GraalVM fixesand improvementsFirst class supportin Spring Boot 3TodayDec 2020BetaSpring Boot 3release
Demo
What’s next?Programmatic configuration for Spring Boot using a Kotlin DSL
Spring Fu is an incubator for a functionalflavor of Spring BootKoFuJaFu
What is the same than Spring Boot? https://start.spring.ioBased on Spring Boot infrastructureSpring configuration for the JVM ecosystemDependency managementStartersActuatorsStandalone executable JAR or container deployment
What changes?Spring Boot regular flavorSpring Fu flavorConventions and automaticconfigurationExplicit declarationAnnotations-based configurationFunctional configurationReflection-based infrastructureLambda-based infrastructureProduction readyIncubating
Spring Boot configured with KoFuval app webApplication {beans {bean SampleService ()bean SampleHandler ()}webMvc {port if (profiles.contains("test")) 8181 else 8080router {val handler ref SampleHandler ()GET("/", handler::hello)GET("/api", handler::json)}converters {string()jackson {indentOutput true}}}}fun main() {app.run()}
pring-fu
Thanks!Have a nice Kotlin!@sdeleuze
Support in Spring Sébastien Deleuze. Spring is the server-side leader on the JVM Source: a Picture of Java in 2020, JetBrains . Spring Framework documentation in Kotlin. Choose your style. Choose your web server stack Do I need asynchronous . 100% of Spring Framework API with null-safety annotations no NPE for Spring applications