如何使用Spring Boot和Spring WebFlux的"功能bean定义Kotlin DSL"?

Jue*_*ann 10 spring kotlin spring-boot spring-webflux

https://github.com/spring-projects/spring-framework/blob/master/spring-context/src/main/kotlin/org/springframework/context/support/BeanDefinitionDsl.kt评论显示如何定义Spring Beans通过新的"功能bean定义Kotlin DSL".我还找到了https://github.com/sdeleuze/spring-kotlin-functional.但是,此示例仅使用普通的 Spring而不是Spring Boot.任何提示如何使用DSL与Spring Boot一起使用表示赞赏.

Séb*_*uze 18

春天引导是基于Java的配置,但应该允许试验支持用户自定义的功能bean声明DSL通过ApplicationContextInitializer所描述的支持在这里.

实际上,您应该能够在Beans.kt包含beans()函数的文件中声明bean .

fun beans() = beans {
    // Define your bean with Kotlin DSL here
}
Run Code Online (Sandbox Code Playgroud)

然后,为了在运行main()和测试时通过Boot考虑它,请创建一个ApplicationContextInitializer类,如下所示:

class BeansInitializer : ApplicationContextInitializer<GenericApplicationContext> {

    override fun initialize(context: GenericApplicationContext) =
        beans().initialize(context)

}
Run Code Online (Sandbox Code Playgroud)

最后,在您的application.properties文件中声明此初始化程序:

context.initializer.classes=com.example.BeansInitializer  
Run Code Online (Sandbox Code Playgroud)

您将在此处找到完整的示例,也可以关注有关功能bean注册的专用Spring Boot支持的此问题.


fg7*_*8nc 7

在 Spring Boot 中执行此操作的另一种方法是:

fun main(args: Array<String>) {
    runApplication<DemoApplication>(*args) {
        addInitializers(
                beans {
                    // Define your bean with Kotlin DSL here
                }
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 该方法的缺点是测试时不会考虑初始化程序。 (4认同)