Spring with MyBatis:预期单个匹配 bean,但发现 2

Ale*_*ord 6 java spring mybatis spring-boot spring-mybatis

我一直在将 Spring 与 MyBatis 一起使用,它在单个数据库中运行得非常好。我在尝试添加另一个数据库时遇到了困难(请参阅Github 上的可重现示例)。

我正在使用 Spring Java 配置(即不是 XML)。我见过的大多数示例都展示了如何使用 XML 实现这一点。

我有两个这样的数据配置类(A & B):

@Configuration
@MapperScan("io.woolford.database.mapper")
public class DataConfigDatabaseA {

    @Bean(name="dataSourceA")
    public DataSource dataSourceA() throws SQLException {
        SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
        dataSource.setDriver(new com.mysql.jdbc.Driver());
        dataSource.setUrl("jdbc:mysql://" + dbHostA + "/" + dbDatabaseA);
        dataSource.setUsername(dbUserA);
        dataSource.setPassword(dbPasswordA);
        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSourceA());
        return sessionFactory.getObject();
    }
}
Run Code Online (Sandbox Code Playgroud)

两个映射器,以及一个自动连接映射器的服务:

@Service
public class DbService {

    @Autowired
    private DbMapperA dbMapperA;

    @Autowired
    private DbMapperB dbMapperB;

    public List<Record> getDabaseARecords(){
        return dbMapperA.getDatabaseARecords();
    }

    public List<Record> getDabaseBRecords(){
        return dbMapperB.getDatabaseBRecords();
    }

}
Run Code Online (Sandbox Code Playgroud)

应用程序不会启动:

Error creating bean with name 'dataSourceInitializer': 
  Invocation of init method failed; nested exception is 
    org.springframework.beans.factory.NoUniqueBeanDefinitionException: 
      No qualifying bean of type [javax.sql.DataSource] is defined: 
        expected single matching bean but found 2: dataSourceB,dataSourceA
Run Code Online (Sandbox Code Playgroud)

我读过可以使用@Qualifier注释来消除自动装配的歧义,但我不确定在哪里添加它。

你能看出我哪里出错了吗?

Ale*_*ord 1

最后,我们将每个映射器放在自己的文件夹中:

src/main/java/io/woolford/database/mapper/a/DbMapperA.java
src/main/java/io/woolford/database/mapper/c/DbMapperB.java
Run Code Online (Sandbox Code Playgroud)

然后我们创建了两个DataConfig类,每个类对应一个数据库。注释@MapperScan解决了这个expected single matching bean but found 2问题。

@Configuration
@MapperScan(value = {"io.woolford.database.mapper.a"}, sqlSessionFactoryRef="sqlSessionFactoryA")
public class DataConfigDatabaseA {
Run Code Online (Sandbox Code Playgroud)

有必要将@Primary注释添加到其中一个类中的 bean DataConfig

@Bean(name="dataSourceA")
@Primary
public DataSource dataSourceA() throws SQLException {
    ...
}

@Bean(name="sqlSessionFactoryA")
@Primary
public SqlSessionFactory sqlSessionFactoryA() throws Exception {
    ...
}
Run Code Online (Sandbox Code Playgroud)

感谢所有提供帮助的人。毫无疑问,有不止一种方法可以做到这一点。我确实按照@eduardlofitskyi 和@GeminiKeith 的建议进行了尝试@Qualifier@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})但这产生了一些进一步的错误。

如果它有用,对我们有用的解决方案发布在这里: https: //github.com/alexwoolford/mybatis-spring-multiple-mysql-reproducible-example