如何使用;功能bean定义Kotlin DSL“;使用Spring Boot和Spring WebFlux?
注释中显示了如何通过新的“函数bean定义Kotlin DSL”定义Springbean。我也发现了。然而,这个例子只使用普通的Spring,而不是Spring引导。任何关于如何将DSL与Spring Boot一起使用的提示,我们都将不胜感激。Spring Boot基于Java配置,但应允许通过如何使用;功能bean定义Kotlin DSL“;使用Spring Boot和Spring WebFlux?,spring,spring-boot,kotlin,spring-webflux,Spring,Spring Boot,Kotlin,Spring Webflux,注释中显示了如何通过新的“函数bean定义Kotlin DSL”定义Springbean。我也发现了。然而,这个例子只使用普通的Spring,而不是Spring引导。任何关于如何将DSL与Spring Boot一起使用的提示,我们都将不胜感激。Spring Boot基于Java配置,但应允许通过ApplicationContextInitializer提供用户定义的实验支持,如前所述 实际上,您应该能够在包含beans()函数的beans.kt文件中声明bean fun beans() = be
ApplicationContextInitializer
提供用户定义的实验支持,如前所述
实际上,您应该能够在包含beans()
函数的beans.kt
文件中声明bean
fun beans() = beans {
// Define your bean with Kotlin DSL here
}
然后,为了在运行main()
和测试时通过引导将其考虑在内,创建一个ApplicationContextInitializer
类,如下所示:
class BeansInitializer : ApplicationContextInitializer<GenericApplicationContext> {
override fun initialize(context: GenericApplicationContext) =
beans().initialize(context)
}
您将找到一个完整的示例,还可以遵循专门的Spring Boot支持功能bean注册。在Spring Boot中实现此功能的另一种方法是:
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args) {
addInitializers(
beans {
// Define your bean with Kotlin DSL here
}
)
}
}
fun main(args:Array){
运行应用程序(*args){
加法器(
豆子{
//在这里用Kotlin DSL定义您的bean
}
)
}
}
您可以在*Config.kt文件中定义bean,并实现ApplicationContextInitializer接口的初始化方法
override fun initialize(applicationContext: GenericApplicationContext) {
....
}
这里有一些bean定义
bean<XServiceImpl>("xService")
bean("beanName") {
BeanConstructor(ref("refBeanName"))
}
bean(“xService”)
豆(“豆名”){
BeanConstructor(参考(“参考BeanName”))
}
您是否尝试过它,例如,通过将此bean定义放入控制器(由spring boot发现)?是的,我尝试了一个带有@bean
方法的@Configuration
类,该方法返回bean{…}
的结果。然后,当我删除@Service
并在bean{…}中声明服务类时,得到了异常“…没有可用的“…”类型的合格bean…”
lambda以上。关于您的答案,有两个问题:*此初始化将由测试设置使用JUnit的SpringRunner
,对吗?*是否有其他方法可以实现这种行为而不必创建属性
文件,包括在测试中进行初始化?谢谢是的,还没有。旁注:我们目前正在探索孵化器项目中使用Java或Kotlin DSL引导的完整功能bean定义。如果我想覆盖bean呢?我添加了allowbean定义overriding:true,并试图通过@bean声明一个测试bean,但它似乎被忽略了。我在一个使用OTU bean DSL的项目上尝试了完全相同的设置(基本上,只是复制粘贴),它成功了。这样声明初始值设定项将禁用spring boot提供的所有其他设置,不是吗?这种方法的缺点是在测试中不会考虑初始值设定项。
bean<XServiceImpl>("xService")
bean("beanName") {
BeanConstructor(ref("refBeanName"))
}