天天看點

Spring Boot 多資料源報錯問題

最近做了個小項目,涉及到多個資料源,覺得挺容易,于是愉快的在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個以上資料源,另個幾個“非主的”資料源會不會沖突?親測發現,不沖突,隻要指定其中一個為主的就行,多個資料源也沒問題。

繼續閱讀