问题描述
在 https://github.com/spring-projects/spring-framework/blob/master/spring-context/src/main/kotlin/org/springframework/context/support/BeanDefinitionDsl.kt 注释显示了如何通过新的"Functional bean definition Kotlin DSL"定义Spring Bean.我还发现了 https://github.com/sdeleuze/spring-kotlin-functional .但是,此示例仅使用 plain Spring,而不使用Spring Boot .任何有关如何将DSL与Spring Boot 一起使用的提示都表示赞赏.
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.
推荐答案
Spring Boot基于Java Config,但应允许对用户定义的功能bean声明DSL 通过ApplicationContextInitializer
支持如此处所述.
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.
实际上,您应该能够在包含beans()
函数的Beans.kt
文件中声明自己的bean.
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
}
然后,为了在运行main()
和测试时使引导程序考虑到它,请创建一个ApplicationContextInitializer
类,如下所示:
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)
}
最后,在您的application.properties
文件中声明此初始化程序:
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.
这篇关于如何使用“功能bean定义Kotlin DSL"?使用Spring Boot和Spring WebFlux?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!