Provide bean conditional registration capabilities in BeanRegistrarDsl

Closes gh-36601
This commit is contained in:
Sébastien Deleuze
2026-04-05 18:49:07 +02:00
parent 82b179f238
commit 2ee4c3a363
2 changed files with 43 additions and 1 deletions
@@ -18,8 +18,8 @@ package org.springframework.beans.factory
import org.springframework.beans.factory.BeanRegistry.SupplierContext
import org.springframework.core.ParameterizedTypeReference
import org.springframework.core.ResolvableType
import org.springframework.core.env.Environment
import kotlin.reflect.KClass
/**
* Contract for registering programmatically beans.
@@ -364,6 +364,28 @@ open class BeanRegistrarDsl(private val init: BeanRegistrarDsl.() -> Unit): Bean
return registry.registerBean(object: ParameterizedTypeReference<T>() {}, customizer)
}
/**
* Determine whether a bean of the given name is already registered.
* @param name the name of the bean
* @since 7.1
*/
fun containsBean(name: String): Boolean = registry.containsBean(name)
/**
* Determine whether a bean of the given type is already registered.
* @param beanType the type of the bean
* @since 7.1
*/
fun containsBean(beanType: KClass<*>): Boolean = registry.containsBean(beanType.java)
/**
* Determine whether a bean of the given type is already registered.
* @param T the type of the bean
* @since 7.1
*/
inline fun <reified T : Any> containsBean(): Boolean =
registry.containsBean(object: ParameterizedTypeReference<T>() {})
/**
* Context available from the bean instance supplier designed to give access
@@ -84,7 +84,13 @@ class BeanRegistrarDslConfigurationTests {
assertThat(context.getBeanProvider<Bar>().singleOrNull()).isNotNull
}
@Test
fun containsBean() {
AnnotationConfigApplicationContext(ContainsBeanRegistrarKotlinConfiguration::class.java)
}
class Foo
data class Bar(val foo: Foo)
data class Baz(val message: String = "")
class Init : InitializingBean {
@@ -145,4 +151,18 @@ class BeanRegistrarDslConfigurationTests {
private class ChainedBeanRegistrar : BeanRegistrarDsl({
register(SampleBeanRegistrar())
})
@Configuration
@Import(ContainsBeanRegistrar::class)
internal class ContainsBeanRegistrarKotlinConfiguration
private class ContainsBeanRegistrar : BeanRegistrarDsl({
assertThat(containsBean("foo")).isFalse()
assertThat(containsBean(Foo::class)).isFalse()
assertThat(containsBean<Foo>()).isFalse()
registerBean<Foo>("foo")
assertThat(containsBean("foo")).isTrue()
assertThat(containsBean(Foo::class)).isTrue()
assertThat(containsBean<Foo>()).isTrue()
})
}