最近做了个小项目,涉及到多个数据源,觉得挺容易,于是愉快的在spring.xml文件里,加上了如下代码:

<!-- 数据源1 -->
    <bean id="DataSource1" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
          destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/trp?useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
        <property name="initialSize" value="1"/>
        <property name="minIdle" value="1"/>
        <property name="maxActive" value="20"/>
    </bean>

    <!-- 数据源2 -->
    <bean id="DataSource2" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
          destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/trp2?useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
        <property name="initialSize" value="1"/>
        <property name="minIdle" value="1"/>
        <property name="maxActive" value="20"/>
    </bean>

结果一启动,报错了:

Description:

Parameter 0 of constructor in org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration required a single bean, but 2 were found:
	- DataSource1: defined in class path resource [spring.xml]
	- DataSource2: defined in class path resource [spring.xml]


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed


Process finished with exit code 1

bean冲突了,明明指定了不用的id,还是报错,万分的不解。试过了几种方法都不行,最后解决了,其实很简单,指定一个主的数据源就行了, 加上:primary="true",如图:

Spring Boot 多数据源报错问题

修改完后,顺利启动。但是又产生疑问,如果有2个以上数据源,另个几个“非主的”数据源会不会冲突?亲测发现,不冲突,只要指定其中一个为主的就行,多个数据源也没问题。

 

相关文章: