问题描述
在Spring Boot和Mybatis项目中配置多个数据源时,发生以下异常:
When configuring multiple datasources in Spring Boot and Mybatis project, following Exception occurs:
项目开始
@SpringBootApplication( exclude = {
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class
})
@EnableTransactionManagement
public class BookSystemApplication {
}
数据源配置
@Configuration
public class DataSourceConfig {
@Bean(name = "primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondDataSource")
@ConfigurationProperties(prefix = "spring.datasource.second")
public DataSource secondDataSource() {
return DataSourceBuilder.create().build();
}
}
交易
@Configuration
public class TransactionConfig {
@Autowired
@Qualifier("primaryDataSource")
private DataSource primary;
@Autowired
@Qualifier("secondDataSource")
private DataSource second;
@Bean(name="primaryTx")
public PlatformTransactionManager primaryTransaction() {
return new DataSourceTransactionManager(primary);
}
@Bean(name="secondTx")
public PlatformTransactionManager secondTransaction() {
return new DataSourceTransactionManager(second);
}
}
推荐答案
这里的问题是,您要将两个beans
定义为datasource
,将两个bean定义为TransactionManager
,但是没有指定其中一个是primary
,将不起作用,因为 Spring
需要一个datasource
bean和一个TransactionManager
bean被定义为主豆 ,如果.
The problem here is that you are defining two beans
as datasource
and two beans as TransactionManager
but you didn't specify which one of them is the primary
one, this won't work because Spring
needs one datasource
bean and one TransactionManager
bean to be defined as primary if more than one are defined.
您应该在这里定义一个数据源beans
和一个TransactionManager beans
为Primary
,这样Spring才能正确运行,您需要使用 @Primary
注释.
What you should do here is to define, one of your datasources beans
and one of your TransactionManager beans
as Primary
, so that Spring can run correctly, to do so you will need to use @Primary
annotation.
@Bean(name = "primaryDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
请参考 Spring的配置两个数据源部分(来自文档).
Please refer to the Spring's Configure two datasources section from the Documentation.
这篇关于当Spring Boot和Mybatis项目中有多个数据源时,出现NoUniqueBeanDefinitionException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!