The annotation will create a bean for each sub-property within the given property. As an example consider the following class:
Using @EachProperty
Using @EachProperty
@EachProperty("test.datasource")
(1)
class DataSourceConfiguration {
final String name
URI url = new URI("localhost")
DataSourceConfiguration(@Parameter String name) (2)
throws URISyntaxException {
this.name = name
}
}
@EachProperty("test.datasource") (1)
class DataSourceConfiguration (2)
@Throws(URISyntaxException::class)
constructor(@param:Parameter val name: String) {
(3)
var url = URI("localhost")
The above DataSourceConfiguration
defines a property to configure one or many hypothetical data sources of some sort. The URLs themselves can be configured using any of the PropertySource instances evaluated to Micronaut:
Providing Configuration to @EachProperty
Providing Configuration to @EachProperty
ApplicationContext applicationContext = ApplicationContext.run(PropertySource.of(
"test",
[
"test.datasource.one.url": "jdbc:mysql://localhost/one",
"test.datasource.two.url": "jdbc:mysql://localhost/two"
]
))
val applicationContext = ApplicationContext.run(PropertySource.of(
"test",
mapOf(
"test.datasource.one.url" to "jdbc:mysql://localhost/one",
"test.datasource.two.url" to "jdbc:mysql://localhost/two"
)
))
In the above example two data sources (called one
and two
) are defined under the test.datasource
prefix defined earlier in the @EachProperty
annotation. Each of these configuration entries triggers the creation of a new DataSourceConfiguration
bean such that the following test succeeds:
Evaluating Beans Built by @EachProperty
Evaluating Beans Built by @EachProperty
when:
Collection<DataSourceConfiguration> beansOfType = applicationContext.getBeansOfType(DataSourceConfiguration.class)
assertEquals(2, beansOfType.size()) (1)
DataSourceConfiguration.class,
Qualifiers.byName("one") (2)
)
then:
new URI("jdbc:mysql://localhost/one") == firstConfig.getUrl()
val beansOfType = applicationContext.getBeansOfType(DataSourceConfiguration::class.java)
assertEquals(2, beansOfType.size.toLong()) (1)
val firstConfig = applicationContext.getBean(
DataSourceConfiguration::class.java,
Qualifiers.byName("one") (2)
)
assertEquals(
URI("jdbc:mysql://localhost/one"),
firstConfig.url
)
1 | All beans of type DataSourceConfiguration can be retrieved using getBeansOfType |
2 | Individual beans can be achieved by using the byName qualifier. |