Use the accepted profiles in BeanDefinitionDsl
Closes gh-22393
This commit is contained in:
committed by
Sebastien Deleuze
parent
ba95818b1d
commit
87c15ba9ad
@@ -23,6 +23,7 @@ import org.springframework.beans.factory.getBeanProvider
|
||||
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils
|
||||
import org.springframework.context.ApplicationContextInitializer
|
||||
import org.springframework.core.env.ConfigurableEnvironment
|
||||
import org.springframework.core.env.Profiles
|
||||
import java.util.function.Supplier
|
||||
|
||||
/**
|
||||
@@ -1082,11 +1083,12 @@ open class BeanDefinitionDsl(private val init: BeanDefinitionDsl.() -> Unit,
|
||||
}
|
||||
|
||||
/**
|
||||
* Take in account bean definitions enclosed in the provided lambda only when the
|
||||
* specified profile is active.
|
||||
* Take in account bean definitions enclosed in the provided lambda when the
|
||||
* profile is accepted.
|
||||
* @see org.springframework.core.env.Profiles.of
|
||||
*/
|
||||
fun profile(profile: String, init: BeanDefinitionDsl.() -> Unit) {
|
||||
val beans = BeanDefinitionDsl(init, { it.activeProfiles.contains(profile) })
|
||||
val beans = BeanDefinitionDsl(init, { it.acceptsProfiles(Profiles.of(profile)) })
|
||||
children.add(beans)
|
||||
}
|
||||
|
||||
|
||||
@@ -170,6 +170,38 @@ class BeanDefinitionDslTests {
|
||||
context.getBean<Baz>()
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
fun `Declare beans with accepted profiles`() {
|
||||
val beans = beans {
|
||||
profile("foo") { bean<Foo>() }
|
||||
profile("!bar") { bean<Bar>() }
|
||||
profile("bar | barbar") { bean<BarBar>() }
|
||||
profile("baz & buz") { bean<Baz>() }
|
||||
profile("baz & foo") { bean<FooFoo>() }
|
||||
}
|
||||
val context = GenericApplicationContext().apply {
|
||||
environment.addActiveProfile("barbar")
|
||||
environment.addActiveProfile("baz")
|
||||
environment.addActiveProfile("buz")
|
||||
beans.initialize(this)
|
||||
refresh()
|
||||
}
|
||||
context.getBean<Baz>()
|
||||
context.getBean<BarBar>()
|
||||
context.getBean<Bar>()
|
||||
|
||||
try {
|
||||
context.getBean<Foo>()
|
||||
fail()
|
||||
} catch (ignored: Exception) {
|
||||
}
|
||||
try {
|
||||
context.getBean<FooFoo>()
|
||||
fail()
|
||||
} catch (ignored: Exception) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Foo
|
||||
|
||||
Reference in New Issue
Block a user