KoFu (for Kotlin and Functional) is an alternative way of configuring explicitly your Spring Boot application, different from regular auto-configuration, using a Kotlin DSL. It is based on Spring Boot infrastructure, but used via functional bean definitions instead of JavaConfig.
It leverages other Spring Kotlin DSLs available in Spring like:
-
beans { }
DSL from Spring Framework -
router { }
DSL from Spring MVC or Spring WebFlux -
security { }
DSL from Spring Security
Here is a sample application that is leveraging Spring MVC:
val app = webApplication {
logging {
level = LogLevel.DEBUG
}
beans {
bean<SampleService>()
}
webMvc {
port = if (profiles.contains("test")) 8181 else 8080
router {
val service = ref<SampleService>()
GET("/") {
ok().body(service.generateMessage())
}
GET("/api") {
ok().body(Sample(service.generateMessage()))
}
}
converters {
string()
jackson {
indentOutput = true
}
}
}
}
data class Sample(val message: String)
class SampleService {
fun generateMessage() = "Hello world!"
}
fun main() {
app.run()
}
To use WebFlux.fn instead
-
Use
reactiveWebApplication
instead ofwebApplication
-
Use
webFlux { }
instead ofwebMvc { }
-
Use
spring-boot-starter-webflux
starter instead ofspring-boot-starter-web
-
Use
coRouter { }
instead ofrouter { }
if you want to use Coroutines instead of Reactor API
-
Go to start.spring.io
-
Select the latest Spring Boot
2.6.x
version -
Add the Spring milestone repository
https://repo.spring.io/milestone
-
Select the "Web" starter
-
Add the
org.springframework.fu:spring-fu-kofu:0.5.1
dependency -
Modify the generated
DemoApplication.kt
file as following:
package com.sample
import org.springframework.fu.kofu.application
val app = webApplication {
...
webMvc {
...
}
}
fun main() {
app.run()
}
See also sample projects here, and more specifically the KoFu tutorial.
You can now also benefit of Spring Framework reference documentation which is now available with Kotlin code samples.