How to use “Functional bean definition Kotlin DSL” with Spring Boot and Spring WebFlux?

后端 未结 3 1263
执笔经年
执笔经年 2021-02-05 19:12

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

相关标签:
3条回答
  • 2021-02-05 19:45

    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.

    0 讨论(0)
  • 2021-02-05 20:06

    Another way to do it in Spring Boot would be :

    fun main(args: Array<String>) {
        runApplication<DemoApplication>(*args) {
            addInitializers(
                    beans {
                        // Define your bean with Kotlin DSL here
                    }
            )
        }
    }
    
    0 讨论(0)
  • 2021-02-05 20:07

    You can define your beans in *Config.kt file and implement initalize method of ApplicationContextInitializer interface.

    override fun initialize(applicationContext: GenericApplicationContext) {
        ....
    }
    

    Some bean definition here.

    bean<XServiceImpl>("xService")
    
    bean("beanName") {
            BeanConstructor(ref("refBeanName"))
    }
    
    0 讨论(0)
提交回复
热议问题