有什么方法可以获取在 Spring Application/Container 中配置为 bean 的所有 javax.sql.DataSource 的集合?

Is there any way to get a collection of all the javax.sql.DataSource that are configured as beans within a Spring Application/Container?

鉴于可以如下构造数据源 bean:

<bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

<bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url2}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

<bean id="dataSource3" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url3}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

有没有一种方法可以获取所有这些数据源的集合,而不必通过它们的标识符显式引用 bean?例如getBean("dataSource3")。容器或应用程序上下文是否提供任何帮助?

本质上给定一个已经定义了所有bean的配置文件,在spring中是否可以实现?

Collection<DataSource> getAllRegisteredDataSources();

非常感谢

是的,您可以采用两种方法来解决此问题。

第一种方法,基本方法,是创建主配置并自动连接附加配置,通过自动连接的上下文,您可以构建数据源集合

  @Configuration
  @Import({ DataSourceAConfig.class }) // Import additional configuration files as required
  public class MasterConfig {

          @Autowired DataSourceAConfig dataSourceAConfigContext; 

            @Bean public List<DataSource> getAllDataSources(){
                 DataSource dataSourceA = dataSourceAConfigContext.getDataSourceBean()
                 // Add data in sequentially way, one after the other 
                return Arrays.asList(dataSourceA);
     }
  }

第二种方法;我推荐的方法是查看 Spring 引导应用程序附带的执行器服务,特别是那些围绕指标的服务。

http://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html

http://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-metrics.html

除了活动数据源的数量之外,它们还提供了额外的信息;包括资源利用和健康检查。

希望对您有所帮助。