At https://github.com/spring-projects/spring-framework/blob/master/spring-context/src/main/kotlin/org/springframework/context/support/BeanDefinitionDsl.kt the comment shows how to define Spring Beans via the new "Functional bean definition Kotlin DSL". I also found https://github.com/sdeleuze/spring-kotlin-functional. However, this example uses just plain Spring and not Spring Boot. Any hint how to use the DSL together with Spring Boot is appreciated.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Spring Boot is based on Java Config, but should allow experimental support of user-defined functional bean declaration DSL via ApplicationContextInitializer
support as described here.
In practice, you should be able to declare your beans for example in a Beans.kt
file containing a beans()
function.
fun beans() = beans {
// Define your bean with Kotlin DSL here
}
Then in order to make it taken in account by Boot when running main()
and tests, create an ApplicationContextInitializer
class as following:
class BeansInitializer : ApplicationContextInitializer<GenericApplicationContext> {
override fun initialize(context: GenericApplicationContext) =
beans().initialize(context)
}
And ultimately, declare this initializer in your application.properties
file:
context.initializer.classes=com.example.BeansInitializer
You will find a full example here and can also follow this issue about dedicated Spring Boot support for functional bean registration.
回答2:
Another way to do it in Spring Boot would be :
fun main(args: Array<String>){
SpringApplicationBuilder().initializers( beans {
// Define your bean with Kotlin DSL here
}).sources(MainClass::class.java).run(*args);