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

    1. @EachProperty("test.datasource")
    2. (1)
    3. class DataSourceConfiguration {
    4. final String name
    5. URI url = new URI("localhost")
    6. DataSourceConfiguration(@Parameter String name) (2)
    7. throws URISyntaxException {
    8. this.name = name
    9. }
    10. }
    1. @EachProperty("test.datasource") (1)
    2. class DataSourceConfiguration (2)
    3. @Throws(URISyntaxException::class)
    4. constructor(@param:Parameter val name: String) {
    5. (3)
    6. 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

    1. ApplicationContext applicationContext = ApplicationContext.run(PropertySource.of(
    2. "test",
    3. [
    4. "test.datasource.one.url": "jdbc:mysql://localhost/one",
    5. "test.datasource.two.url": "jdbc:mysql://localhost/two"
    6. ]
    7. ))
    1. val applicationContext = ApplicationContext.run(PropertySource.of(
    2. "test",
    3. mapOf(
    4. "test.datasource.one.url" to "jdbc:mysql://localhost/one",
    5. "test.datasource.two.url" to "jdbc:mysql://localhost/two"
    6. )
    7. ))

    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

    1. when:
    2. Collection<DataSourceConfiguration> beansOfType = applicationContext.getBeansOfType(DataSourceConfiguration.class)
    3. assertEquals(2, beansOfType.size()) (1)
    4. DataSourceConfiguration.class,
    5. Qualifiers.byName("one") (2)
    6. )
    7. then:
    8. new URI("jdbc:mysql://localhost/one") == firstConfig.getUrl()
    1. val beansOfType = applicationContext.getBeansOfType(DataSourceConfiguration::class.java)
    2. assertEquals(2, beansOfType.size.toLong()) (1)
    3. val firstConfig = applicationContext.getBean(
    4. DataSourceConfiguration::class.java,
    5. Qualifiers.byName("one") (2)
    6. )
    7. assertEquals(
    8. URI("jdbc:mysql://localhost/one"),
    9. firstConfig.url
    10. )
    1All beans of type DataSourceConfiguration can be retrieved using getBeansOfType
    2Individual beans can be achieved by using the byName qualifier.