spring autowire多次实现

时间:2015-09-15 21:36:51

标签: java spring

我需要自动连接具有几个实现的接口。我使用@Qualifier来实现这一目标 -

接口DataSourceConfig

public interface DataSourceConfig {
  DataSource getDataSource();
}

实施1:

@Configuration("mysql")
public class MySqlDataSourceConfig implements DataSourceConfig {

@Bean
public DataSource getDataSource() {
    System.out.println("MySQL datasource");

    //some implementation

    return dataSource;
 }
}

实施2:

@Configuration("hsql")
public class HsqlDataSourceConfig implements DataSourceConfig {

@Bean
public DataSource getDataSource() {
    System.out.println("hsql dataSource");
    return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL).addScript(
            "classpath:database/schema.sql").addScript(
            "classpath:database/datascript.sql").build();
   }
}

客户端:

@Configuration
public class Client {

 @Autowired
 @Qualifier("hsql")
 DataSourceConfig hsqlDataSource;

 @Autowired
 @Qualifier("mysql")
 DataSourceConfig mysqlDataSource;

}

只创建了一个数据源(mysqlDataSource),我在日志中看到以下消息。它虽然在INFO模式下 -

org.springframework.beans.factory.support.DefaultListableBeanFactory.registerBeanDefinition Overriding bean definition for bean 'hsqlDataSource':

1 个答案:

答案 0 :(得分:0)

要解决多个相同类型(DataSource)的问题,我们必须使用自动装配模式"按名称"。默认值为"按类型"。设置属性" name"到你的@Bean注释。

实施1:

@Configuration
public class MySqlDataSourceConfig implements DataSourceConfig {

    @Bean(name="mysql")
    public DataSource getDataSource() {
        System.out.println("MySQL datasource");
        MysqlDataSource dataSource= new MysqlDataSource();
        // ... dataSource parameters
        return dataSource;
     }
}

实施2:

@Configuration
public class HsqlDataSourceConfig implements DataSourceConfig {

    @Bean(name="hsql")
    public DataSource getDataSource() {
     System.out.println("hsql dataSource");
     return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL).addScript(
        "classpath:database/schema.sql").addScript(
        "classpath:database/datascript.sql").build();
   }
}

<强>客户端:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class Client {

    @Autowired
    @Qualifier("hsql")
    private javax.sql.DataSource hsqlDataSource;

    @Autowired
    @Qualifier("mysql")
    private javax.sql.DataSource mySqlDataSource;
}