4.7 Using @EachBean to Drive Configuration
The @EachProperty is a great way to drive dynamic configuration, but typically you want to inject that configuration into another bean that depends on it. Injecting a single instance with a hard coded qualifier is not a great solution, hence @EachProperty
is typically used in combination with @EachBean:
Using @EachBean
@Factory (1)
public class DataSourceFactory {
@EachBean(DataSourceConfiguration.class) (2)
DataSource dataSource(DataSourceConfiguration configuration) { (3)
URI url = configuration.getUrl();
return new DataSource(url);
}
Using @EachBean
@Factory (1)
class DataSourceFactory {
@EachBean(DataSourceConfiguration.class) (2)
DataSource dataSource(DataSourceConfiguration configuration) { (3)
URI url = configuration.getUrl()
return new DataSource(url)
}
Using @EachBean
@Factory (1)
class DataSourceFactory {
@EachBean(DataSourceConfiguration::class) (2)
internal fun dataSource(configuration: DataSourceConfiguration): DataSource { (3)
val url = configuration.url
return DataSource(url)
}
1 | The above example defines a bean Factory that will create instances of javax.sql.DataSource . |
2 | The @EachBean annotation is used to indicate that a new DataSource bean should be created for each DataSourceConfiguration defined in the previous section. |
3 | The DataSourceConfiguration instance is injected as a method argument and used to drive the configuration of each javax.sql.DataSource |
Note that @EachBean
requires that the parent bean has a @Named
qualifier, since the qualifier is inherited by each bean created by @EachBean
.
In other words, to retrieve the DataSource
created by test.datasource.one
you can do:
Using a Qualifier
Collection<DataSource> beansOfType = applicationContext.getBeansOfType(DataSource.class);
assertEquals(2, beansOfType.size()); (1)
DataSource firstConfig = applicationContext.getBean(
DataSource.class,
Qualifiers.byName("one") (2)
);
Using a Qualifier
when:
Collection<DataSource> beansOfType = applicationContext.getBeansOfType(DataSource.class)
assertEquals(2, beansOfType.size()) (1)
DataSource firstConfig = applicationContext.getBean(
DataSource.class,
Qualifiers.byName("one") (2)
)
Using a Qualifier
val beansOfType = applicationContext.getBeansOfType(DataSource::class.java)
assertEquals(2, beansOfType.size.toLong()) (1)
val firstConfig = applicationContext.getBean(
DataSource::class.java,
Qualifiers.byName("one") (2)
)
1 | We demonstrate here that there are indeed two data sources. How can we get one in particular? |
2 | By using Qualifiers.byName(“one”) , we can select which of the two beans we’d like to reference. |