【发布时间】:2016-07-11 02:53:12
【问题描述】:
我一直在将 Spring 与 MyBatis 一起使用,它在单个数据库中运行得非常好。我在尝试添加另一个数据库时遇到了困难(请参阅reproducible example on 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();
}
}
两个映射器和一个自动装配映射器的服务:
@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();
}
}
应用程序无法启动:
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
我读到可以使用 @Qualifier 注释来消除自动装配的歧义,但我不确定在哪里添加它。
你能看出我哪里错了吗?
【问题讨论】:
-
你能发布完整的错误信息吗?通常spring会告诉你自动装配的字段和导致错误的bean。
-
@Qaulifier("name_of_bean")可以放在我相信您要定位的特定字段的@Autowired注释之前或之后 -
谢谢@Ben75。我将完整的输出发布到:gist.github.com/alexwoolford/1f3e799deb3be32a4356
-
您是否尝试过在配置中手动创建 dataSourceInitializer(s) 而不是隐式创建它们?
标签: java spring spring-boot mybatis spring-mybatis