springspring-bootkotlinspring5spring-bean-dsl

Spring Kotlin Bean DSL - register bean only if other bean is present?


I want to register bean (MyBean) only if another bean (anotherBeanThatShouldBePresent) is present in the context.

How I can achieve that?

bean {
    MyBean(
        anotherBeanThatShouldBePresent = ref()
    )
}

Solution

  • You can use ObjectProvider to create bean depending on another bean

    bean {
        provider<OtherBeanOnWhichIDepend>().ifAvailable {
            bean<MyCustomBean>()
        }
    }
    

    With this code I will register MyCustomBean only if OtherBeanOnWhichIDepend bean is available