Fix Kotlin bean DSL conditional handling

Issue: SPR-16412
This commit is contained in:
Sebastien Deleuze
2018-06-01 14:24:51 +02:00
parent 356bfe6e2e
commit b71d0eeec9
2 changed files with 18 additions and 12 deletions

View File

@@ -195,7 +195,7 @@ open class BeanDefinitionDsl(private val init: BeanDefinitionDsl.() -> Unit,
autowireMode: Autowire = Autowire.NO,
isAutowireCandidate: Boolean? = null,
crossinline function: () -> T) {
val customizer = BeanDefinitionCustomizer { bd ->
scope?.let { bd.scope = scope.name.toLowerCase() }
isLazyInit?.let { bd.isLazyInit = isLazyInit }
@@ -255,9 +255,11 @@ open class BeanDefinitionDsl(private val init: BeanDefinitionDsl.() -> Unit,
*/
override fun initialize(context: GenericApplicationContext) {
this.context = context
for (child in children) {
child.initialize(context)
}
init()
for (child in children) {
if (child.condition.invoke(context.environment)) {
child.initialize(context)
}
}
}
}

View File

@@ -52,18 +52,21 @@ class BeanDefinitionDslTests {
@Test
fun `Declare beans using profile condition with the functional Kotlin DSL`() {
val beans = beans {
bean<Foo>()
bean<Bar>("bar")
profile("baz") {
profile("pp") {
bean<Foo>()
profile("foo") {
bean<Foo>()
profile("bar") {
bean<Bar>("bar")
}
}
profile("baz") {
bean { Baz(ref()) }
bean { Baz(ref("bar")) }
}
}
val context = GenericApplicationContext().apply {
environment.addActiveProfile("foo")
environment.addActiveProfile("bar")
beans.initialize(this)
refresh()
}
@@ -82,7 +85,9 @@ class BeanDefinitionDslTests {
val beans = beans {
bean<Foo>()
bean<Bar>("bar")
bean { FooFoo(env["name"]!!) }
environment( { env["name"].equals("foofoo") } ) {
bean { FooFoo(env["name"]!!) }
}
environment( { activeProfiles.contains("baz") } ) {
bean { Baz(ref()) }
bean { Baz(ref("bar")) }
@@ -97,13 +102,12 @@ class BeanDefinitionDslTests {
assertNotNull(context.getBean<Foo>())
assertNotNull(context.getBean<Bar>("bar"))
assertEquals("foofoo", context.getBean<FooFoo>().name)
try {
context.getBean<Baz>()
fail("Expect NoSuchBeanDefinitionException to be thrown")
}
catch(ex: NoSuchBeanDefinitionException) { null }
val foofoo = context.getBean<FooFoo>()
assertEquals("foofoo", foofoo.name)
}
@Test // SPR-16412