Skip to content

Commit f72e0da

Browse files
committed
Add an env accessor to BeanDefinitionContext
Issue: SPR-15755
1 parent c292a89 commit f72e0da

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

spring-context/src/main/kotlin/org/springframework/context/support/BeanDefinitionDsl.kt

+9-2
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
package org.springframework.context.support
1818

1919
import org.springframework.beans.factory.config.BeanDefinitionCustomizer
20-
import org.springframework.context.ApplicationContext
2120
import org.springframework.core.env.ConfigurableEnvironment
2221
import java.util.function.Supplier
2322

@@ -38,12 +37,20 @@ open class BeanDefinitionDsl(val condition: (ConfigurableEnvironment) -> Boolean
3837
PROTOTYPE
3938
}
4039

41-
class BeanDefinitionContext(val context: ApplicationContext) {
40+
class BeanDefinitionContext(val context: GenericApplicationContext) {
4241

42+
4343
inline fun <reified T : Any> ref(name: String? = null) : T = when (name) {
4444
null -> context.getBean(T::class.java)
4545
else -> context.getBean(name, T::class.java)
4646
}
47+
48+
/**
49+
* Get the [ConfigurableEnvironment] associated to the underlying [GenericApplicationContext].
50+
*/
51+
val env : ConfigurableEnvironment
52+
get() = context.environment
53+
4754
}
4855

4956
/**

spring-context/src/test/kotlin/org/springframework/context/support/BeanDefinitionDslTests.kt

+8-1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import org.junit.Test
2121
import org.springframework.beans.factory.NoSuchBeanDefinitionException
2222
import org.springframework.beans.factory.getBean
2323
import org.springframework.context.support.BeanDefinitionDsl.*
24+
import org.springframework.core.env.SimpleCommandLinePropertySource
2425

2526
class BeanDefinitionDslTests {
2627

@@ -75,13 +76,16 @@ class BeanDefinitionDslTests {
7576
val beans = beans {
7677
bean<Foo>()
7778
bean<Bar>("bar")
79+
bean { FooFoo(it.env.getProperty("name")) }
7880
environment({it.activeProfiles.contains("baz")}) {
7981
bean { Baz(it.ref()) }
8082
bean { Baz(it.ref("bar")) }
8183
}
8284
}
8385

84-
val context = GenericApplicationContext()
86+
val context = GenericApplicationContext().apply {
87+
environment.propertySources.addFirst(SimpleCommandLinePropertySource("--name=foofoo"))
88+
}
8589
beans.invoke(context)
8690
context.refresh()
8791

@@ -92,10 +96,13 @@ class BeanDefinitionDslTests {
9296
fail("Expect NoSuchBeanDefinitionException to be thrown")
9397
}
9498
catch(ex: NoSuchBeanDefinitionException) { null }
99+
val foofoo = context.getBean<FooFoo>()
100+
assertEquals("foofoo", foofoo.name)
95101
}
96102

97103
}
98104

99105
class Foo
100106
class Bar
101107
class Baz(val bar: Bar)
108+
class FooFoo(val name: String)

0 commit comments

Comments
 (0)