出现NoUniqueBeanDefinitionExceptio

出现NoUniqueBeanDefinitionExceptio

本文介绍了当Spring Boot和Mybatis项目中有多个数据源时,出现NoUniqueBeanDefinitionException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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 beansPrimary,这样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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 09:27